The findIndex() Method in JavaScript
If you want to find the first matching element from an array but need its index, use the findIndex() method. It returns the index of the first matching element. If nothing is found, it returns -1.
Syntax
array.findIndex(function(element, index, array) {
// returns true/false
});
Parameters
- element - the current element
- index - the current index
- array - the entire array
Simple Example
const users = [
{ id: 1, name: 'Anna' },
{ id: 2, name: 'David' },
{ id: 3, name: 'Levon' }
];
const foundIndex = users.findIndex(user => user.id === 2);
console.log(foundIndex); // 1
In this case, findIndex() returns the index of the 2nd element that matches id: 2.
If Nothing is Found
const result = users.findIndex(user => user.id === 5);
console.log(result); // -1
Comparison with find()
- find() returns the first matching element.
- findIndex() returns the index of the first matching element.
const even = [1, 2, 3, 4, 5];
const found = even.find(n => n % 2 === 0); // 2
const foundIndex = even.findIndex(n => n % 2 === 0); // 1
How findIndex() Works Internally
When we call:
[1, 2, 3].findIndex(fn);
This is equivalent to:
Array.prototype.findIndex.call([1, 2, 3], fn);
Implement Our Own myFindIndex() Function from Scratch
function myFindIndex(array, callback) {
for (let i = 0; i < array.length; i++) {
if (callback(array[i], i, array)) {
return i;
}
}
return -1;
}
Let's apply it:
const items = [10, 20, 30, 40];
const foundIndex = myFindIndex(items, function(item) {
return item > 25;
});
console.log(foundIndex); // 2
Add It as a Method to the Array Prototype
Array.prototype.myFindIndex = function(callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return i;
}
}
return -1;
};
Usage:
const numbers = [5, 10, 15, 20];
const foundIndex = numbers.myFindIndex(n => n > 10);
console.log(foundIndex); // 2
Conclusion
- Use findIndex() when you need to find the index of the first matching element.
- Returns -1 if nothing is found.
- If you need the index, use findIndex().