Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.filter

Creates a new array from the elements that pass a test.

Available since: ES5

Syntax

array.filter(callbackFn)

Parameters

ParameterTypeDescription
callbackFnFunctionA test function: an element is kept when it returns `true`.

Return value

ArrayA new array with the selected elements; empty if none matched.

Examples

Even numbers only:

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

Output:

2, 4

Selecting objects by a property:

const tasks = [
  { title: 'Tea', done: true },
  { title: 'Coffee', done: false },
];
 
console.log(tasks.filter((task) => !task.done).length);

Output:

1

Notes

The source array is not modified. To get a single element rather than an array, use find().

See also

Related recipes

In the tutorial

  • map, filter and reduce — The three main array processing methods in JavaScript: transforming, selecting and reducing to a single value.

Thanks for reading!

Donate to the site — we work hard for you.