find, some & every

Search arrays and test whether items match.

Syntaxarr.find(item => condition)

Three handy searching methods:

  • find() — returns the first item that passes the test, or undefined.
  • some() — returns true if at least one item passes.
  • every() — returns true if all items pass.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Retrieve a specific user object from a list by their unique id after receiving it from an API event.
  • Find the first product below a budget threshold to highlight it as the best value option.
  • Locate the first unread notification in a notifications array to scroll to and highlight it.

More examples

Find object by id

Returns the first user whose id matches 2, or undefined if not found.

Example · js
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Carol" }
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Bob" }

findIndex for position

Uses findIndex to get the position of the first completed task in the array.

Example · js
const tasks = [
  { id: "t1", done: false },
  { id: "t2", done: true },
  { id: "t3", done: false }
];
const idx = tasks.findIndex(t => t.done);
console.log(idx); // 1

find vs filter comparison

Contrasts find (returns the first match) with filter (returns all matches) on the same predicate.

Example · js
const items = [3, 7, 12, 5, 9];
// find: stops at first match
const first = items.find(n => n > 6);
// filter: collects all matches
const all = items.filter(n => n > 6);
console.log(first); // 7
console.log(all);   // [7, 12, 9]

Discussion

  • Be the first to comment on this lesson.