EN
JavaScript - find last index of element inside array by certain condition
1
answers
0
points
How can I find last index of element inside array by certain condition?
Let's say I have a following array:
var objects = [
{ id: 1, type: 'A' },
{ id: 2, type: 'B' },
{ id: 3, type: 'A' },
{ id: 4, type: 'B' },
{ id: 5, type: 'A' }
];
My goal is to find the index of the last object which type property value is equal to B.
In this case it should be 3 (index of { id: 4, type: 'B' }).
Is there a function for that?
1 answer
0
points
You can use findIndex() method on reversed array.
The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. Used on reversed array will give you the last index.
Note:
Use
slice()to copy the original array becausereverse()method will mutate it.
Practical example
// ONLINE-RUNNER:browser;
function findLastIndex(array, key, value) {
var index = array
.slice()
.reverse()
.findIndex(function(x) {
return x[key] === value;
});
var count = array.length - 1;
var finalIndex = index >= 0 ? count - index : index;
return finalIndex;
}
// Usage example:
var objects = [
{ id: 1, type: 'A' },
{ id: 2, type: 'B' },
{ id: 3, type: 'A' },
{ id: 4, type: 'B' },
{ id: 5, type: 'A' },
];
console.log(findLastIndex(objects, 'type', 'B')); // 3
console.log(findLastIndex(objects, 'type', 'C')); // -1
References
0 comments
Add comment