How to Use find and findIndex in JavaScript
Getting the first matching item, or its index, from an array.
You may encounter times when you need one specific item out of an array, like
the user with a certain id or the first product that's out of stock. Looping
through the whole array and keeping track of a match works, but find and
findIndex do it in one line.
find() returns the first item that passes your test. findIndex() returns
the position of that item.
Using find
find runs your callback on each item until the callback returns a truthy
value, then it hands you back that item:
const users = [{ id: 1, name: "Jim" },{ id: 2, name: "Pam" },{ id: 3, name: "Dwight" },]const pam = users.find((user) => user.id === 2)console.log(pam) // { id: 2, name: "Pam" }
It stops as soon as it finds a match, so it won't keep checking the rest of the array.
If nothing matches you get undefined, so check before you use the result:
const michael = users.find((user) => user.name === "Michael")console.log(michael) // undefinedif (michael) {console.log(michael.name)}
Using findIndex
findIndex works the same way, but returns the index of the match instead of
the item. If nothing matches it returns -1:
const index = users.findIndex((user) => user.id === 3)console.log(index) // 2const missing = users.findIndex((user) => user.id === 10)console.log(missing) // -1
This comes in handy when you need to update or remove an item in place:
const todos = [{ id: 1, text: "Write post", done: false },{ id: 2, text: "Publish post", done: false },]const todoIndex = todos.findIndex((todo) => todo.id === 1)if (todoIndex !== -1) {todos[todoIndex].done = true}
find vs filter
find gives you one item. filter gives you an array of every item that
matches. If you only expect a single result, like looking something up by id,
find is simpler since you don't have to grab [0] off the result.
const firstLong = ["hi", "hello", "howdy"].find((word) => word.length > 3)// "hello"
Note: find and findIndex aren't supported in Internet Explorer. If you
need to support it, add a polyfill or use a for loop.
Have some feedback on this post? .