const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filter = arr.filter((number) => number > 5);
console.log(filter); // [6, 7, 8, 9]
const products = [
{ name: 'Laptop', price: 32000, brand: 'Lenovo', color: 'Silver' },
{ name: 'Phone', price: 700, brand: 'Iphone', color: 'Golden' },
{ name: 'Watch', price: 3000, brand: 'Casio', color: 'Yellow' },
{ name: 'Aunglass', price: 300, brand: 'Ribon', color: 'Blue' },
{ name: 'Camera', price: 9000, brand: 'Lenovo', color: 'Gray' },
];
//Get products that price is greater than 3000 by using a filter
const getProduct = products.filter(product => product.price > 3000);
console.log(getProduct)
//Expected output:
/*[
{ name: 'Laptop', price: 32000, brand: 'Lenovo', color: 'Silver' },
{ name: 'Camera', price: 9000, brand: 'Lenovo', color: 'Gray' }
]
*/
// filter takes an array and function as argumentfunction
filter(arr, filterFunc) {
const filterArr = []; // empty array
// loop though array
for(let i=0;i<arr.length;i++) {
const result = filterFunc(arr[i], i, arr);
// push the current element if result is true
if(result)
filterArr.push(arr[i]);
}
return filterArr;
}