JavaScript Array filter() Method
Example
Return the array ages containing all elements greater than 18:
var
ages = [
32
,
33
,
16
,
40
];
function
checkAdult(age) {
return
age >=
18
;
}
function
myFunction() {
document.getElementById(
"demo"
).innerHTML = ages.filter(checkAdult);
}
The output result is:
32,33,40
Try it »
Definition and Usage
The filter() method creates a new array with all elements that pass the condition in the specified array.
Note: filter() does not check empty arrays.
Note: filter() does not change the original array.
Browser support
The numbers in the table indicate the first browser version that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| filter() | Yes | 9 | 1.5 | Yes | Yes |
Syntax
array.filter(function(currentValue,index,arr), thisValue)
Parameter Description
| Parameters | Description |
|---|---|
| function(currentValue, index,arr) | Required. A function that is executed for each element in the array |
函数参数:
Parameter Description currentValue Required. The value of the current element index Optional. The index of the current element arr Required. The array object to which the current element belongs | Parameter | Description | *currentValue* | Required. The value of the current element | *index* | Optional. The index of the current element | *arr* | Optional. The array object to which the current element belongs | | Parameter | Description | | *currentValue* | Required. The value of the current element | | *index* | Optional. The index of the current element | | *arr* | Optional. The array object to which the current element belongs | | *thisValue* | Optional. An object passed to the function as the value of "this" when the callback is executed. 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 array ages that are greater than the value specified in the input box:
Minimum age: "number"
id=
"ageToCheck"
value=
"18"
JavaScript Array object