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 »
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
array.filter(function(currentValue, index, arr), thisValue)
Parameters
Parameter
Description
function()
Required.
A function to run for each array element.
A function to run for each array element.
currentValue
Required.
The value of the current element.
The value of the current element.
index
Optional.
The index of the current element.
The index of the current element.
arr
Optional.
The array of the current element.
The array of the current element.
thisValue
Optional. Default
A value passed to the function as its
undefinedA value passed to the function as its
this value.
Return Value
Type
Description
Array
An array of elements that pass the test.
An empty array if no elements pass the test.
An empty array if no elements pass the test.
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 »
<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 |