The _.findIndex()
method in Lodash is used to find the index of an element inside an array. This method iterates over the array from start to end to find the index.
_.findIndex(array, predicate, startIndex)
This method accepts the following parameters:
array
: This is the array to be inspected.predicate
: This is the function that is checked against the values of the array in every iteration.startIndex
: This is the index to where the search starts. If not specified, it will take 0 as default.This method returns the index of the element if found. Otherwise, it returns -1.
Let’s look at an example of the _.findIndex()
method in the code snippet below:
In the HTML tab:
lodash
script.In the JavaScript tab:
_.findIndex()
method to find the index of the person whose name is Josh.There are 2 people with the name Josh in the array. As we discussed earlier, this method iterates from start to end. Thus, we see the index of the first element that matches our predicate from the start of the array on the console.