The JavaScript array filter() method filters and extracts the element of an array that satisfies the provided condition.
In this tutorial, you will learn how to use the JavaScript Array filter()
method to filter elements in an array.
The filter()
method does not execute the function for empty elements.
JavaScript Array filter() method doesn’t change the original array.
filter()
is an ECMAScript5 (ES5) feature.
Syntax
array.filter(callbackFunction(currentValue, index, arr), thisValue)
Parameters
This method accepts five parameter as mentioned above and described below:
- callbackFunction– It represents the function that test the condition.
- currentValue– The current element of array.
- index – It is optional. The index of current element.
- arr – It is optional. The array on which filter() operated.
- thisArg – It is optional. The value to use as this while executing callback.
Return Value
A new array containing the filtered elements.
Examples
Below are the examples of the Array filter() method.
The following example uses filter()
to create a filtered array that has all elements with values less than 10
removed.
function isBigEnough(value) {
return value >= 10
}
let filtered = [12, 5, 8, 130, 44].filter(isBigEnough)
// filtered is [12, 130, 44]
The following example returns all prime numbers in the array:
onst array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i == 0) {
return false;
}
}
return num > 1;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]