Lodash _.findIndex() Method
Loadsh _.findIndex() method is used to find the index of the first occurrence of the element. It is different from indexOf because it takes the predicate function that iterates through each element of the array.
Syntax:
_.findIndex(array, [predicate=_.identity], fromIndex);
Parameters:
- array: It is the array in which the value is to be searched.
- predicate: It is the function that iterate through each element.
- fromIndex: It is the index after which the element is to be searched. If from index is not given by default it will be 0.
Return Value:
It returns the index of the element if found else -1 is returned.
Example 1: In this example, an element is searched starting from index 0 and printing the result according to the arrow function used in the _.findIndex() method.
Javascript
const _ = require( 'lodash' );
let array1 = [4, 2, 3, 1, 4, 2]
let index = _.findIndex(array1, (e) => {
return e == 1;
}, 0);
console.log( "original Array: " , array1)
console.log( "index: " , index)
|
Output:
Example 2: In this example, an element is looked after some index “i”. Here element is present in the array but still the output is -1 because it is present at index 3 and the searching starts from index 5.
Javascript
const _ = require( 'lodash' );
let array1 = [4, 2, 3, 1, 4, 2]
let index = _.findIndex(array1, (e) => {
return e == 1;
}, 5);
console.log( "original Array: " , array1)
console.log( "index: " , index)
|
Output:
Last Updated :
25 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...