filter() method is used to create a new array with all elements that pass the test implemented by the provided function.
Syntax:
const newArray = array.filter(callback(element, index, array), thisArg);
callback: A function that is called for every element of the array. If this function returns true, the element is included in the new array.
element: The current element being processed in the array.
index (Optional): The index of the current element being processed in the array.
array (Optional): The array that filter() was called upon.
thisArg (Optional): Value to use as this when executing the callback function.
It can be particularly useful if you want to filter out certain values from an array of strings:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // Expected output: ['exuberant', 'destruction', 'present']
const products = [ { name: 'Laptop', price: 1000 }, { name: 'Phone', price: 500 }, { name: 'Tablet', price: 300 }, { name: 'Monitor', price: 200 }, { name: 'Keyboard', price: 50 }, ]; const expensiveProducts = products.filter(product => product.price > 500); console.log(expensiveProducts); // Expected output: // [ // { name: 'Laptop', price: 1000 }, // { name: 'Phone', price: 500 } // ]