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 »
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.
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 |
Array |
An array of elements that 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 »
Related Pages:
Browser Support
filter()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all modern browsers since July 2013:
Chrome 23 |
IE/Edge 10 |
Firefox 21 |
Safari 6 |
Opera 15 |
Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.