JavaScriptEasy
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.
find | filter | |
|---|---|---|
| Returns | One element or undefined | Array (can be empty) |
| Stops early | Yes, at the first match | No, checks all |
| Use for | Looking 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: justtrue/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
findcan returnundefined: 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.lengthor usesome.
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];67console.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"]910console.log(users.find((u) => u.id === 99)); // undefined11console.log(users.filter((u) => u.id === 99)); // []12console.log(users.find((u) => u.id === 99)?.name ?? "not found"); // not found1314// Searching from the end15console.log(users.findLast((u) => u.role === "admin").name); // Grace1617// The empty-array trap18if (users.filter((u) => u.role === "owner")) console.log("always runs - [] is truthy");19console.log(users.some((u) => u.role === "owner")); // false - the right check2021// Repeated lookups: build a Map once22const 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.