Easy Tutorial
❮ Prop Element Offsetparent Jsref Obj Global ❯

JavaScript Array filter() Method

JavaScript Array Object

Example

Return all elements in the ages array that 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

Definition and Usage

The filter() method creates a new array with all elements that pass the test implemented by the provided 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 Chrome IE Firefox Safari Opera
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 to be run for each element in the array. <br>Function arguments: <br>currentValue - Required. The value of the current element. <br>index - Optional. The array index of the current element. <br>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. <br>If this parameter is empty, the value "undefined" will be passed as its "this" value.

Technical Details

Return Value: An array containing all the elements that pass the test. If no elements pass the test, it returns an empty array.
JavaScript Version: 1.6

More Examples

Example

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

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Click me</button>
<p>All elements greater than the specified value are: <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>

JavaScript Array Object

❮ Prop Element Offsetparent Jsref Obj Global ❯