JavaScript Array filter()
- Previous Page fill()
- Next Page find()
- Go Back to the Previous Level JavaScript Array Reference Manual
Definition and Usage
filter()
The method creates an array filled with all array elements that pass the test (as a function provided).
Note:filter()
This function will not be executed for array elements without values.
Note:filter()
It will not change the original array.
Example
Example 1
Return an array consisting of all values 18 years of age or older in the ages array:
var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult); }
Example 2
Return an array consisting of all values greater than or equal to a specific number in the ages array:
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p> <button onclick="myFunction()">Try it</button> <p>All ages above minimum: <span id="demo"></span></p> <script> var ages = [32, 33, 12, 40]; function checkAdult(age) { return age >= document.getElementById("ageToCheck").value; } function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult); } </script>
Syntax
array.filter(function(currentValue, index, arr) thisValue)
Parameter value
Parameter | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | Required. A function to be run for each element in the array.
Function parameters:
|
||||||||
thisValue |
Optional. The 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 array elements that pass the test. If no elements pass the test, an empty array is returned. |
---|---|
JavaScript version: | ECMAScript 5 |
Browser support
All browsers fully support filter()
Method:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9.0 | Support | Support | Support | Support |
Related Pages
Tutorial:JavaScript Array
Tutorial:JavaScript Array Const
Tutorial:JavaScript Array Methods
Tutorial:JavaScript Sorting Arrays
Tutorial:JavaScript Array Iteration
- Previous Page fill()
- Next Page find()
- Go Back to the Previous Level JavaScript Array Reference Manual