The filter()
method returns a new array with all elements that pass the test defined by the given function.
Example
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// function to check even numbers
function checkEven(number) {
if (number % 2 == 0)
return true;
else
return false;
}
// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);
// Output: [ 2, 4, 6, 8, 10 ]
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
true
if element passes the test, elsefalse
. It takes in:- element - The current element being passed from the array.
- thisArg (optional) - The value to use as
this
when 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 executecallback
for array elements without values.
Example 1: Filtering out values from Array
const prices = [1800, 2000, null, 3000, 5000, "Thousand", 500, 8000]
function checkPrice(element) {
return element > 2000 && !Number.isNaN(element);
}
let filteredPrices = prices.filter(checkPrice);
console.log(filteredPrices); // [ 3000, 5000, 8000 ]
// using arrow function
let newPrices = prices.filter((price) => (price > 2000 && !Number.isNaN(price)));
console.log(newPrices); // [ 3000, 5000, 8000 ]
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
const languages = ["JavaScript", "Python", "Ruby", "C", "C++", "Swift", "PHP", "Java"];
function searchFor(arr, query) {
function condition(element) {
return element.toLowerCase().indexOf(query.toLowerCase()) !== -1;
}
return arr.filter(condition);
}
let newArr = searchFor(languages, "ja");
console.log(newArr); // [ 'JavaScript', 'Java' ]
// using arrow function
const searchArr = (arr, query) => arr.filter(element => element.toLowerCase().indexOf(query.toLowerCase()) !== -1);
let newLanguages = searchArr(languages, "p");
console.log(newLanguages); // [ 'JavaScript', 'Python', 'PHP' ]
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()