JavaScript Array filter()
Example 1
Return an array of all values in ages[] that are 18 or over:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Try it Yourself »
Definition and Usage
The filter()
method creates a new array filled with elements that pass a test provided by a function.
The filter()
method does not execute the function for empty elements.
The filter()
method does not change the original array.
Syntax
array.filter(function(currentValue, index, arr), thisValue)
Parameters
Parameter | Description |
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined A value passed to the function as its this value. |
Return Value
Type | Description |
An array |
Containing the elements that pass the test. If no elements pass the test it returns an empty array. |
Example 2
Return the values in ages[] that are over a specific number:
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>
Try it Yourself »
Browser Support
filter()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |