Array.prototype.filter()

Creates a new array with all elements that pass the test in the callback.

Since ES5 Spec ↗

Syntax

arr.filter(callback, thisArg)

Parameters

NameTypeRequiredDescription
callback Function Yes Predicate called for each element with (element, index, array). Return truthy to keep the element.
thisArg any No Value to use as `this` when executing the callback.

Returns

Array — A new array with the elements that passed the test; empty if none pass.

Examples

const nums = [1, 2, 3, 4, 5];
console.log(nums.filter(n => n % 2 === 0));
Output
[ 2, 4 ]
const words = ['a', '', 'b', null];
console.log(words.filter(Boolean));
Output
[ 'a', 'b' ]

Notes

Does not mutate the original array. Skips empty slots in sparse arrays. Returns a new array; to find a single element use `find` instead.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.5
safari 3.0
edge 12
node 0.10

See also