How to use the filter() method In Javascript
The filter() method is a built-in function for arrays in JavaScript that creates a new array with all elements that pass the test implemented by the provided callback function. It iterates over each element of the array and applies the callback function to each element. If the callback function returns true for an element, that element is included in the new array; otherwise, it is excluded.
Syntax:
const newArray = originalArray.filter(callbackFunction(element[, index[, array]])[, thisArg]);
Parameters:
- callbackFunction: A function to test each element of the array. It takes 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 array filter() was called upon.
- thisArg (Optional): Value to use as this when executing the callback.
Example : To demonstrate filtering the array elements in JavaScript using filter() method.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers
.filter(number => number % 2 === 0);
console.log(evenNumbers);
Output
[ 2, 4 ]
How to Filter an Array in JavaScript ?
Filtering an array in JavaScript involves selecting elements based on certain criteria. The selected elements form a new array. This operation is integral to tasks such as data manipulation, data processing, and displaying filtered results. The function tests each element in the array and includes it in the filtered array if it meets the criteria, otherwise it is excluded.
This operation is commonly used in JavaScript programming for tasks such as data manipulation, data processing, and displaying filtered results to users.
Table of Content
- Using the filter() method
- Using a for loop
- Using the reduce() method
Contact Us