What is the _.findLastIndex() method in Lodash?

Overview

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.

Syntax

_.findLastIndex(array, predicate, startIndex)
Syntax of _.findLastIndex() method

Parameters

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.

Return value

This method returns the index of the element, if found, otherwise it returns -1.

Example

Let’s look at an example of the _.findLastIndex() method in the code snippet below:

Console
Implementation of the _.findLastIndex() method

Explanation

In the HTML tab:

  • Line 5: We import the lodash script.

In the JavaScript tab:

  • Lines 2–7: We create an array of objects.
  • Line 9: We use the _.findLastIndex() method to find the index of the person whose name is Josh.
  • Line 11: We print the output to the console.

Output

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.

Free Resources