JavaScript Array filter()
Example 1
Return an array of all values in ages[] that are 18 or over:
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Description
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.
Array Iteration Methods:
Syntax
Parameters
A function to run for each array element.
The value of the current element.
The index of the current element.
The array of the current element.
undefinedA value passed to the function as its
this value.
Return Value
An empty array if no elements pass the test.
Example 2
Return the values in ages[] that are over a specific number:
<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>
Array Tutorials:
Browser Support
filter() is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
| Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
| Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |