javascript

Lodash - Find item index from array by searching from the end

To find the item index from an array that searches from the array end or from right to left, you can use the lodash method - _.findLastIndex.

var subjects = [
    { 'name': 'Math', 'score': 70 },
    { 'name': 'Physics', 'score': 80 },
    { 'name': 'Chemistry', 'score': 80 },
    { 'name': 'English', 'score': 90 }
];

//It starts searching items from end
// Find index where subject name is Chemistry
const physics_index = _.findLastIndex(subjects, function (item) {
    return item.name == 'Physics'; 
});
console.log("Physics index is : " + physics_index);
// => 1

//Find Index where score is 80
const score_index = _.findLastIndex(subjects, ['score', 80]);
console.log(score_index);
//=> 2

_.findLastIndex() Lodash

_.findLastIndex(Array, Predicate, FromIndex=Array.length-1)

Parameters Information

Array: [Required].

Predicate: [Required] - a function that invokes each iteration.

FromIndex:[Optional] Index value from where you want to start the search for the item. Default value is  Array.length-1.

The iterstion starts from right to left and the function returns index if it find the item or returns -1.

Example Demo

Was this helpful?