The _.findLastIndex()
method in Lodash is used to find the index of an element inside an array. This method iterates over the array from end to start to find the index.
_.findLastIndex(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 where the search is started. If not specified, it will take the length of the array as default.This method returns the index of the element, if found, otherwise it returns -1.
Let’s look at an example of the _.findLastIndex()
method in the code snippet below:
In the HTML tab:
lodash
script.In the JavaScript tab:
_.findLastIndex()
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 end to start. Thus, we see the index of the first element that matches our predicate from the end of the array, on the console.