Javascript - Array filter() Method

The filter() method creates an array filled with all array elements that pass a test.

Description

The filter() method creates an array filled with all array elements that pass a test.

filter() does not run the function for array elements without values.

filter() does not change the original array.

Syntax

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

Parameter Values

Parameter Require Description
function(currentValue, index,arr) Required.A function to be run for each element in the array.
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

For function(currentValue, index,arr)

Argument Require 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

Return

An Array containing all the array elements that pass the test. If no elements pass the test it returns an empty array.

Example

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

Demo

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

function checkAdult(age) {
    return age >= 18;
}
console.log( ages.filter(checkAdult));//from www  .j av  a2s  . c  om

Result