The FindIndex Method
What you'll learn: How to find the position of the first element in an array that passes a test, or get -1 if none do.
What FindIndex Does
While find() returns the element itself, findIndex() returns the position (index) of that element in the array. It takes a predicate function and runs it on each element until it finds one that passes the test. If nothing matches, it returns -1.
Think of it like telling someone: "I don't need the book itself—just tell me which shelf number it's on, or tell me if you don't have it."
Basic Syntax
const numbers = [10, 25, 30, 45];
const index = numbers.findIndex(function(num) {
return num > 20;
});
console.log(index); // 1 (the element 25 is at index 1)
With Arrow Functions
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Carol', age: 35 }
];
const index = users.findIndex(user => user.age > 30);
console.log(index); // 2 (Carol is at index 2)
When Nothing Matches
const numbers = [1, 2, 3];
const index = numbers.findIndex(num => num > 10);
console.log(index); // -1 (no element passed the test)
Why Use FindIndex?
You need findIndex() when you want to modify or remove an element based on a condition, since you need its position in the array:
const tasks = ['email', 'code', 'meeting'];
const index = tasks.findIndex(task => task === 'code');
if (index !== -1) {
tasks[index] = 'coding complete';
}
Key Takeaway: Use findIndex() to get the index of the first matching element, receiving -1 if no matches exist—perfect when you need position rather than the element itself.