The filter() method returns a new array with all elements that pass the test defined by the given function.
Example
filter() Syntax
The syntax of the filter() method is:
arr.filter(callback(element), thisArg)
Here, arr is an array.
filter() Parameters
The filter() method takes in:
- callback - The test function to execute on each array element; returns
trueif element passes the test, elsefalse. It takes in:- element - The current element being passed from the array.
- thisArg (optional) - The value to use as
thiswhen executing callback. By default, it isundefined.
filter() Return Value
- Returns a new array with only the elements that passed the test.
Notes:
filter()does not change the original array.filter()does not executecallbackfor array elements without values.
Example 1: Filtering out values from Array
Output
[ 3000, 5000, 8000 ] [ 3000, 5000, 8000 ]
Here, all the numbers less than or equal to 2000, and all the non-numeric values are filtered out.
Example 2: Searching in Array
Output
[ 'JavaScript', 'Java' ] [ 'JavaScript', 'Python', 'PHP' ]
Here, element and query both are converted to lowercase, and the indexOf() method is used to check if query is present inside element.
Those elements that do not pass this test are filtered out.
Recommended Reading: JavaScript Array map()