The _.indexOf()
method in Lodash is used to get the index of the first occurrence of a value from an array.
_.indexOf(array, value, startIndex)
This method accepts the following parameters:
array
: This is the array to be queried.value
: This is the value to be searched.startIndex
: This is the index from where the search starts. If not specified, it will take 0 as default. If negative, it will serve as an offset from the end of the array.
This method returns the index of the value if found. Otherwise, it returns -1.
Let’s look at an example of the _.indexOf()
method in the code snippet below:
In the HTML tab:
lodash
script.In the JavaScript tab:
numbers
and populate it with a few values.value
and initialize it with 3
._.indexOf()
method to find the index of the value.In the output, we see 2
, which is the index of the value 3
in the array numbers
.