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

Overview

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.

Syntax

_.findIndex(array, predicate, startIndex)

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 to where the search starts. If not specified, it will take 0 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 _.findIndex() method in the code snippet below:

Console
Implementation of the _.findIndex() method

Explanation

In the HTML tab:

  • Line 5: We import the lodash script.

In the JavaScript tab:

  • Line 2–6: We create an array of objects.
  • Line 9: We use the _.findIndex() 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 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.

Free Resources