Table of Contents
What findIndex() Does
Returns the position of the first match: it gives you a number, the index, not the item.
Stops at the first match: later items never get checked.
Takes a condition: so it can handle logic, like "greater than 10" or "has this ID".
Leaves the original array alone: it only reads through it.
let numbers = [5, 12, 8, 20, 3]; let index = numbers.findIndex(n => n > 10); console.log(index); // 1
Syntax and Parameters
array.findIndex(function (item, index, array) {
return condition;
});
item: the current element being checked.
index: its position in the array.
array: the full array. You'll rarely need it.
The function must return true or false: that decides whether the item counts as a match.
Practical Examples
Finding the position of an object:
let users = [
{ id: 1, name: "Vi" },
{ id: 2, name: "Sam" },
{ id: 3, name: "Alex" }
];
let index = users.findIndex(u => u.id === 2);
console.log(index); // 1
Updating an item at that position:
let tasks = [
{ id: 1, title: "Study", done: false },
{ id: 2, title: "Gym", done: false }
];
let i = tasks.findIndex(t => t.id === 2);
if (i !== -1) {
tasks[i].done = true;
}
Removing an item at that position:
let j = tasks.findIndex(t => t.id === 1);
if (j !== -1) {
tasks.splice(j, 1);
}
Things to Remember
No match gives you -1: not undefined, and not an error.console.log([1, 2, 3].findIndex(n => n > 100)); // -1
Check against -1 explicitly: a quick truthy check goes wrong, because index 0 is falsy.
let arr = [100, 200, 300]; let i = arr.findIndex(n => n === 100); console.log(i); // 0 console.log(!i); // true, looks like "not found" but isn't console.log(i !== -1); // true, the correct checkOnly the first match counts: if several items pass, you only get one index.
Common Mistakes
Using if (!index) to check for not found: this treats a valid index of 0 as a miss.
Using splice with -1: splice(-1, 1) removes the last item, so always check for -1 first.
Forgetting to return a value: with curly braces, you need an explicit return, otherwise it always returns -1.
Conclusion
Frequently Asked Questions (FAQs)
2.Why does findIndex() return -1 when nothing matches?find() returns the matching item. findIndex() returns its position.
3.Can findIndex() search an array of objects?Because it returns a position, and -1 is the usual way to say "not found" for an index.
Yes. You can write a condition on any property, which indexOf() can't do.
0 Comments