Understanding Array.prototype.findIndex()
What you'll learn: How to locate the position of an element in an array using findIndex().
In the previous lesson, you learned that find() returns the element itself. But what if you need to know where that element lives in the array? That's where findIndex() comes in.
What findIndex() Does
findIndex() searches an array from left to right and returns the index (position) of the first element that satisfies your test function. If no element passes the test, it returns -1.
Think of it like asking "At what address does this person live?" rather than "Who is this person?" You get the location, not the item itself.
Basic Syntax
const numbers = [5, 12, 8, 130, 44];
const firstLargeIndex = numbers.findIndex(num => num > 10);
console.log(firstLargeIndex); // 1 (the number 12 is at index 1)
The -1 Return Value
When nothing matches, findIndex() returns -1:
const numbers = [1, 2, 3];
const result = numbers.findIndex(num => num > 100);
console.log(result); // -1 (no element is greater than 100)
This -1 convention is consistent across JavaScript's searching methods like indexOf().
Practical Example
const users = [
{ id: 10, name: 'Alice' },
{ id: 20, name: 'Bob' },
{ id: 30, name: 'Charlie' }
];
const bobIndex = users.findIndex(user => user.name === 'Bob');
console.log(bobIndex); // 1
// Now you can use that index for other operations
if (bobIndex !== -1) {
console.log(`Bob is at position ${bobIndex}`);
}
Key Takeaway: findIndex() returns the index of the first element matching your condition, or -1 if nothing matches—use it when you need the position rather than the element itself.