THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Array filter() Method

JavaScript Array Reference JavaScript Array Reference

Example

Return an array of all the values in the ages array that are 18 or over:

var ages = [32, 33, 16, 40];

function checkAdult(age) {
    return age >= 18;
}

function myFunction() {
    document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}

The result will be:

32,33,40
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 as a function).

Note: filter() does not execute the function for array elements without values.

Note: filter() does not change the original array.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
filter() Yes 9.0 1.5 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:
Argument Description
currentValue Required. The value of the current element
index Optional. The array index of the current element
arr Optional. The array object the current element belongs to
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: 1.6

Examples

More Examples

Example

Return an array of all the values in the ages array that are a specific number or over:

<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>
Try it Yourself »

JavaScript Array Reference JavaScript Array Reference