Array.filter

filter — Creates a new array with all elements that pass the test implemented by the provided function.

Description

Array.filter(function callback, [object this])

Parameters

Name Description Type Default Optional
callback See callback below. function No
this object Yes
callback

The following parameters is passed to the callback.

value

The value of the current index.

index

The current index.

array

The array.

Return values

Returns a new array with all the values from the passed iterations.

Examples

Example #1 – filter example
var array = [2, 4, 8]; var result = array.filter(function () { console.log(this); return true; }); console.log(result); // [2, 4, 8]
var arr = [2, 4, 8]; var result = arr.filter(function (value, index, array) { console.log(value, index, array); return true; }); console.log(result); // [2, 4, 8]

Passing in a custom object for this.

var array = [2, 4, 8]; var result = array.filter(function () { console.log(this); return true; }, document.location); console.log(result); // [2, 4, 8]

Emulates a failed test when the value 4 is discovered.

var array = [2, 4, 8]; var result = array.filter(function (value) { if (value === 4) { return false; } return true; }); console.log(result); // [2, 8] console.log(array); // [2, 4, 8]

External references