Latest web development tutorials

JavaScript Array filter () method

Array Object Reference JavaScript Array Object

Examples

Returns an array of ages in all of the elements are larger than 18 elements:

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

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

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

The output is:

32, 33

try it"

Definition and Usage

filter () method creates a new array of new elements in the array is specified by examining all of the elements in the array qualifying.

Note: filter () does not detect an empty array.

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


Browser Support

Figures in the table represent the first browser to support the method version number.

method
filter () Yes 9 1.5 Yes Yes

grammar

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

Parameter Description

parameter description
function (currentValue, index, arr) have to. Function, each element of the array will perform this function function parameters:
parameter description
currentValue have to. The value of the current element
index Optional. The index value of the current element
arr Optional. An array of objects belonging to the current element
thisValue Optional. As the callback object use, passed to the function, it is used as "this" value.
If you omit thisValue, "this" value "undefined"

technical details

return value: It returns an array that contains all elements of the condition. If there is no qualifying element returns an empty array.
JavaScript version: 1.6

More examples

Examples

Returns an array of ages in all of the elements are larger than the specified input box element values:

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

<P> All of the elements are larger than the specified array? <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.every (checkAdult);
}
</ Script>
try it"

Array Object Reference JavaScript Array Object