Open In App

Lodash _.lastIndexOf() Method

Lodash _.lastIndexOf() method is like the _.indexOf method except that it iterates over elements of an array from right to left.

Syntax:

_.lastIndexOf(array, value, [fromIndex=array.length-1]);

Note: If the value is not found in the array -1 is returned.



Parameters:

Return Value:

It returns the index of the value in the array. If the value is not found, the array returns -1.

Example 1: In this example, we are finding the index of the 2 in a given array by the use of the _lastIndexOf() method.






// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array = [1, 2, 2, 3, 4]
 
// Printing original array 
console.log("Array : ", array)
 
// Looking for value 3 from Last index  
let index = _.lastIndexOf(array, 2)
 
// Printing the Index of the value 
console.log("Index : ", index)

Output:

Example 2: In this example, we are finding the index of the 2 from 2 index number in a given array by the use of the _lastIndexOf() method.




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array = [1, 2, 2, 3, 4, 2]
 
// Printing original array 
console.log("Array : ", array)
 
// Looking for value 3 from Last index  
let index = _.lastIndexOf(array, 2, 2)
 
// Printing the Index of the value 
console.log("Index : ", index)

Output:

Example 3: In this example, we are finding the index of the 4 in a given array by the use of the _lastIndexOf() method and it is returning -1 as it is not present in that array.




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array = [1, 2, 2, 3, 4, 2]
 
// Printing original array 
console.log("Array : ", array)
 
// Looking for value 3 from Last index  
let index = _.lastIndexOf(array, 4, 2)
 
// Printing the Index of the value 
console.log("Index : ", index)

Output:


Article Tags :