Array.prototype.filter
Creates a new array from the elements that pass a test.
Available since: ES5
Syntax
array.filter(callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A 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, 4Selecting objects by a property:
const tasks = [
{ title: 'Tea', done: true },
{ title: 'Coffee', done: false },
];
console.log(tasks.filter((task) => !task.done).length);Output:
1Notes
The source array is not modified. To get a single element rather than an array, use find().
See also
- Array.prototype.map — Creates a new array by transforming every element.
- Array.prototype.find — Returns the first element that passes a test.
- Array.prototype.every — Checks that every element of an array passes a test.
Related recipes
- How to check password strength
- How to count characters in a string
- How to count occurrences of values in an array
- How to count words in a string
- How to filter an array
- How to find an element in an array by a condition
- How to find common elements of two arrays
- How to find duplicates in an array
- How to find the difference between two arrays
- How to list the files in a folder in Node.js
- How to remove an element from an array
- How to remove duplicate objects by a field
- How to remove duplicates from an array
- How to remove empty values from an array
- How to split text into lines
In the tutorial
- map, filter and reduce — The three main array processing methods in JavaScript: transforming, selecting and reducing to a single value.