iteration

Array.prototype.filter

Creates a new array containing every element for which the callback returned a truthy value. Reach for it to pare a list down to items matching a predicate.

arr.filter(callbackFn[, thisArg])

Parameters

Parameter Purpose
callbackFn(element, index, array) Predicate — return truthy to keep the element
thisArg Value used as `this` inside callbackFn

Examples

console.log([1,2,3,4].filter(n => n % 2 === 0));

Logs: [2, 4]

console.log(['a','','b',null,'c'].filter(Boolean));

Logs: ['a', 'b', 'c'] (drops falsy)

const users = [{age:12},{age:30},{age:8}]; console.log(users.filter(u => u.age >= 18));

Logs: [{age: 30}]

console.log([1,2,3].filter(n => n > 99));

Logs: [] (no match returns empty array, not undefined)

Gotcha

Always returns a new array (never null/undefined) — check `.length` not truthiness on the result. Truthy/falsy rules apply: 0, '', null, undefined, NaN are all dropped by `filter(Boolean)`.

Related methods

← All JS array methods · TypeScript vs JavaScript