In React JS , the filter() method is a built-in JavaScript function that creates a new array with all elements that pass a test implemented by a provided function. It does not modify the original array, but rather creates a new array with the elements that pass the test.
Here’s the syntax for using the filter() method:
const newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
arr: The array to be filtered.callback: A function that tests each element of the array. This function is called with three arguments: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 arrayfilter()was called upon.
thisArg(optional): A value to be passed to thecallbackfunction as thethisvalue.
The callback function should return a boolean value indicating whether the element should be included in the new array or not. If the callback function returns true, the element is included in the new array. If the callback() function returns false, the element is not included in the new array.
Here’s an example of using the filter() method to create a new array with only even numbers:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
In this example, we call the filter() method on the numbers array and pass a callback function that tests each element to see if it is an even number. If the element is an even number, the callback function returns true, and the element is included in the new evenNumbers array. If the element is an odd number, the callback function returns false, and the element is not included in the new evenNumbers array.
You can also use the filter() method to filter an array of objects based on a certain condition. Here’s an example of filtering an array of objects based on a specific property value:
const products = [
{ name: 'apple', price: 1.99 },
{ name: 'banana', price: 0.99 },
{ name: 'mango', price: 2.99 },
{ name: 'orange', price: 1.49 }
];
const cheapProducts = products.filter(product => product.price < 2);
console.log(cheapProducts);
/* Output:
[
{ name: 'apple', price: 1.99 },
{ name: 'banana', price: 0.99 },
{ name: 'orange', price: 1.49 }
]
*/
In this example, we call the filter() method on the products array and pass a callback function that tests each element to see if its price property is less than 2. If the price property is less than 2, the callback function returns true, and the element is included in the new cheapProducts array. If the price property is greater than or equal to 2, the callback function returns false, and the element is not included in the new cheapProducts array.
