The findIndex()
method in Javascript is used to find an element in an array. The method returns the index of the first element that satisfies the given condition in the callback function. It returns -1
if no element is found matching the criteria.
let numbers = [5, 6, 7, 8, 9];
let search = numbers.findIndex(function (n) {
return n == 8;
});
console.log(search); // 3
If the element is not found,
let numbers = [5, 6, 7, 8, 9];
let search = numbers.findIndex(function (n) {
return n == 10;
});
console.log(search); // -1
This method is useful when you are interested in getting the index of the element. If you want to return the element you can use the find() method.
The callback function can be passed a second argument which is the index
and the third argument array
which is the array on which the findIndex() method is called.
let numbers = [5, 6, 7, 8, 9];
let search = numbers.findIndex(function (element, index, arr) {
console.log(index);
console.log(arr);
return element == 10;
});
console.log(search); // -1
/*
Output:
0
[5, 6, 7, 8, 9]
1
[5, 6, 7, 8, 9]
2
[5, 6, 7, 8, 9]
3
[5, 6, 7, 8, 9]
4
[5, 6, 7, 8, 9]
*/