Arrays
array.find()
Finds the first item that matches a condition.
Why it exists
Very often you need one specific item from a list: the user with this id, the product selected in the cart, the first overdue payment. filter is awkward for that — it returns an array and walks the whole list. find stops at the first match and returns the item itself.
Where it's used
- Find a record by
id:products.find((p) => p.id === id). - The first match: the first free slot in a schedule, the first unread message.
- Check and get data: find a user by email at sign-in.
findIndex— to then replace or remove an item by position.
Syntax
array.find((item) => condition)
array.findIndex((item) => condition)Examples
const users = [{ id: 1, name: "Ann" }, { id: 2, name: "Bob" }];
users.find((u) => u.id === 2); // → { id: 2, name: "Bob" }
users.find((u) => u.id === 9); // → undefinedconst slots = ["9:00", "10:00", "11:00"];
const busy = ["9:00"];
slots.find((s) => !busy.includes(s)); // → "10:00"const nums = [4, 7, 9];
nums.findIndex((n) => n > 5); // → 1
nums.findIndex((n) => n > 100); // → -1findIndex — a position or -1Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
find calls the callback for items in order. As soon as the callback returns a truthy value, find returns that item and looks no further. If none matches, it returns undefined.
You get the item itself, not a copy: if it's an object, changes to it show up in the array too.
findIndex works the same but returns the index, or -1 when nothing is found. There are also versions that search from the end: findLast and findLastIndex.
Traps
How it differs from…
array.filter()filter returns an array of every match and always walks the whole list.
findreturns one item and stops at the first.some()andevery()some only answers "is there one?" (
true/false);findreturns the item itself.
When to pick something else
Practice
Lessons where this appears
- The conveyor at the fish factoryTale · Chapter 10 · map, filter, reduce
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- A shift on the conveyorWorkshop · Chapter 10 · map, filter, reduce
- The jammed conveyorBoss · Chapter 10 · map, filter, reduce
- A cart classLab · Chapter 14 · this and classes
- The case of the missing customersInvestigation · Chapter 26 · Debugging