JavaScript's findIndex method
Details, examples, practice
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.
array.findIndex(function(element, index, array) { // returns true/false });
Parameters
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.
const result = users.findIndex(user => user.id === 5); console.log(result); // -1
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
When we call:
[1, 2, 3].findIndex(fn);
This is equivalent to:
Array.prototype.findIndex.call([1, 2, 3], fn);
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
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