Languages

JavaScript - find last index of element inside array by certain condition

0 points
Asked by:
Aran-Busby
592

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
Answered by:
Aran-Busby
592

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 because reverse() 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

  1. Array.prototype.slice() - JavaScript | MDN
  2. Array.prototype.reverse() - JavaScript | MDN
  3. Array.prototype.findIndex() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join