JavaScript Array filter()
Example
Return an array of all the values in ages[] that are 18 or over:
const ages = [32, 33, 16, 40];
ages.filter(checkAdult) // Returns [32, 33, 40]
function checkAdult(age) {
return age >= 18;
}
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The filter() method creates an array filled with all array elements that pass a
test (provided by a function).
filter() does not execute the function for empty array elements.
filter() does not change the original array.
Browser Support
filter() is fully supported in all modern browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | 9.0 | Yes | Yes | Yes | Yes |
Syntax
array.filter(function(currentValue, index, arr), thisValue)
Parameter Values
| Parameter | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index,arr) | Required. A function to be run for each element in the array. Function arguments:
|
||||||||
| thisValue | Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value |
Technical Details
| Return Value: | An Array containing all the array elements that pass the test. If no elements pass the test it returns an empty array. |
|---|---|
| JavaScript Version: | ECMAScript 5 |
More Examples
Example
Return the values in ages[] that are over a specific number:
<p><input type="number" id="ageToCheck" value="18"></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 »

