Chrome Extension

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
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

_.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

Search Index Data (The code snippet can also be found with below search text)

_.findLastIndex lodash
Was this helpful?
0 Comments