Array.prototype.filter()
The counterpart to map: map changes each element and keeps the length, filter keeps each element and changes the length. Reaching for the wrong one is the commonest Array mix-up.
Demo
Only the elements that satisfy the test survive, so the output is usually shorter than the input — that is the whole difference from map. When nothing passes you get an empty array rather than null or undefined, which means you can always safely chain another array method onto the result.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| callback | Function | yes | Called as callback(element, index, array). The element is kept when the return value is truthy. |
| thisArg | any | no (undefined) | Value of `this` inside the callback. Ignored for arrow functions. |
Return value
Array — A NEW array holding only the elements for which the callback returned a truthy value. The original array is never modified.
Common patterns
const clean = values.filter(Boolean);
const names = users.filter(u => u.active).map(u => u.name);
const rest = items.filter(i => i.id !== targetId);
Examples
Pitfalls
[1, 2, 3].filter(x => { x > 1 })
[1, 2, 3].filter(x => x > 1)
[{n: 0}, {n: 1}].filter(o => o.n)
[{n: 0}, {n: 1}].filter(o => o.n !== undefined)
[1, 2].filter(x => x * 10)
[1, 2].map(x => x * 10)
users.filter(u => u.id === 1)
users.find(u => u.id === 1)
When to use
- Narrowing an array to the elements that matter
- Removing falsy values with filter(Boolean)
- Non-mutating removal, as an alternative to splice
- You want to change each element → map
- You want exactly one match → find
- You only need to know whether any match → some
- You are reducing to a single value → reduce
Notes
FAQ
Almost always because the callback returns nothing. An arrow function with braces needs an explicit return — without it every element yields undefined, which is falsy, so nothing survives.
[1, 2, 3].filter(x => { x > 1 }) // [] [1, 2, 3].filter(x => x > 1) // [2, 3]