Difference between find() and filter()?

find() returns the first element that matches (or undefined) and stops searching immediately; filter() returns a new array of all matching elements (possibly empty) and always checks every element.

findfilter
ReturnsOne element or undefinedArray (can be empty)
Stops earlyYes, at the first matchNo, checks all
Use forLooking up one item by id, name, etc.Getting every matching item

Related methods

  • findIndex: index of the first match, or -1.
  • findLast / findLastIndex (ES2023): search from the end, handy for "the most recent X".
  • some: just true/false, stops at the first match.
  • includes: for primitive values (list.includes("a")).

Common mistakes

  • Using filter(...)[0] to get one item: it works but scans the whole array.
  • Forgetting find can return undefined: use optional chaining (find(...)?.name) or handle the "not found" case.
  • Checking if (filter(...)): an empty array is truthy, so this is always true. Check .length or use some.

Lookups in big lists

If you look up by id repeatedly, build a Map once (new Map(items.map(i => [i.id, i]))) and use map.get(id), which is O(1) instead of O(n) per lookup.

Code example

js
1const users = [
2 { id: 1, name: "Ada", role: "admin" },
3 { id: 2, name: "Linus", role: "user" },
4 { id: 3, name: "Grace", role: "admin" },
5];
6
7console.log(users.find((u) => u.role === "admin")); // { id: 1, name: "Ada", role: "admin" }
8console.log(users.filter((u) => u.role === "admin").map((u) => u.name)); // ["Ada", "Grace"]
9
10console.log(users.find((u) => u.id === 99)); // undefined
11console.log(users.filter((u) => u.id === 99)); // []
12console.log(users.find((u) => u.id === 99)?.name ?? "not found"); // not found
13
14// Searching from the end
15console.log(users.findLast((u) => u.role === "admin").name); // Grace
16
17// The empty-array trap
18if (users.filter((u) => u.role === "owner")) console.log("always runs - [] is truthy");
19console.log(users.some((u) => u.role === "owner")); // false - the right check
20
21// Repeated lookups: build a Map once
22const byId = new Map(users.map((u) => [u.id, u]));
23console.log(byId.get(2).name); // Linus

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