What is the filter() method?

filter() returns a new array containing only the elements for which the callback returns a truthy value; it never changes the original array and the result can be any length, including empty.

Signature

array.filter((element, index, array) => keep, thisArg?)

Typical uses

  • Search results: items whose name includes a query.
  • Removing items immutably: todos.filter(t => t.id !== idToDelete), the standard way to delete from React state.
  • Cleaning data: values.filter(Boolean) removes null, undefined, 0, "", NaN and false.
  • Removing duplicates (small arrays): list.filter((x, i) => list.indexOf(x) === i). For large arrays use a Set.

Things to know

  • filter always walks the whole array. If you only need the first match, use find (or some for a yes/no), which stop early.
  • The returned elements are the same objects, not copies. Mutating them changes the originals.
  • filter(Boolean) also drops 0, which is a bug when zeros are valid values. Be explicit: filter(x => x != null).
  • In TypeScript, a type predicate ((x): x is User => ...) lets filter narrow the resulting type.

Chaining

filter pairs naturally with map and reduce. For very large arrays, a single reduce or loop avoids creating intermediate arrays.

Code example

js
1const users = [
2 { name: "Ada", age: 36, active: true },
3 { name: "Linus", age: 17, active: false },
4 { name: "Grace", age: 45, active: true },
5];
6
7const activeAdults = users.filter((u) => u.active && u.age >= 18);
8console.log(activeAdults.map((u) => u.name)); // ["Ada", "Grace"]
9
10// Immutable delete (React-style)
11const remaining = users.filter((u) => u.name !== "Linus");
12console.log(remaining.length, users.length); // 2 3
13
14// Search
15const query = "a";
16console.log(users.filter((u) => u.name.toLowerCase().includes(query)).length); // 2
17
18// filter(Boolean) drops ALL falsy values, including 0
19const raw = [0, 1, null, 2, "", 3, undefined, NaN];
20console.log(raw.filter(Boolean)); // [1, 2, 3]
21console.log(raw.filter((x) => x != null && !Number.isNaN(x) && x !== "")); // [0, 1, 2, 3]
22
23// Need just one? find stops at the first match
24console.log(users.find((u) => u.age > 40)?.name); // Grace

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app