Find the Index
findIndex returns the index of the first item that matches.
If nothing matches, it returns -1.
JavaScript Tutorial
findIndex returns the position of the first item that matches a condition.
It is useful when you need to update or remove items by index.
Many updates require the index of an item. findIndex gives you that quickly.
It stops early, so it is efficient for lookups.
array.findIndex((value, index, array) => condition)const users = [{ id: 1 }, { id: 2 }];
const idx = users.findIndex((u) => u.id === 2);
console.log(idx);Returns 1 for the item with id 2.
const nums = [1, 2, 3];
const idx = nums.findIndex((n) => n > 10);
console.log(idx); // -1-1 indicates no match.
findIndex returns the index of the first item that matches.
If nothing matches, it returns -1.
Once you have the index, you can update or remove the item.
This is useful in state updates and list editing.
Like find, it stops after the first match.
That makes it efficient for lookups.
const items = [{ id: 1, done: false }];
const idx = items.findIndex((i) => i.id === 1);
if (idx !== -1) items[idx].done = true;
console.log(items);Use the index to update a specific item.
const list = ["a", "b", "c"];
const idx = list.findIndex((v) => v === "b");
if (idx !== -1) list.splice(idx, 1);
console.log(list);Remove an item by index.
Without
let idx = -1;
for (let i = 0; i < users.length; i++) {
if (users[i].id === 2) {
idx = i;
break;
}
}With
const idx = users.findIndex((u) => u.id === 2);Always check if index is -1 before using it.
findIndex returns the position, not the item.
Use filter or a loop to collect all matches.
-1.
When you need the position to update or remove.
Yes, it stops early.
Practice: Find the index of the first negative number.
const nums = [3, -1, 4];
// TODO: find index of first negative
One Possible Solution
const nums = [3, -1, 4];
const idx = nums.findIndex((n) => n < 0);
console.log(idx);The index of the first match or -1.
Use find when you need the element, not the index.
No, it does not.
Try changing the array to see different indexes.