JavaScript Array filter() Method

Array 对象参考手册JavaScript Array Object

Example

Return arrayageselements in which all elements are greater than 18:

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

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

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

Output result:

32,33,40

Try it Yourself »

Definition and Usage

The filter() method creates a new array containing all elements that pass the test implemented by the provided function.

Note:filter() does not test empty arrays.

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 1.5 Yes Yes

Syntax

array.filter(function(currentValue,index,arr), thisValue)

Parameter Details

Parameter Description
function(currentValue, index,arr) Required. A function that will be executed for each element in the array.
Function parameters:
Parameter Description
currentValue Required. The value of the current element.
index Optional. The index of the current element.
arr Optional. The array object the current element belongs to.
thisValue Optional. An object to use as "this" when executing the callback, passed to the function.
If thisValue is omitted, the value of "this" is "undefined".

Technical Details

Return value: Returns an array containing all elements that meet the condition. If no elements meet the condition, an empty array is returned.
JavaScript Version: 1.6

More Examples

Example

Return all elements in the ages array that are greater than the value specified in the input box:

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Click me</button>

<p>What elements are greater than the specified value? <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 »

Array 对象参考手册JavaScript Array Object

Other Extensions