JS Last index of a non-null element in an array

Viewed 6177

I have an array with defined and null values inside, like so :

var arr = [
  {...},
  null,
  null,
  {...},
  null
];

Is there any way for me to get the index of the last non-null element from this array? And I mean without having to loop through it entirely.

5 Answers

You can use the map function to iterate through the array, check the condition and return the index, then take the maximum index:

Math.max.apply(null, arr.map(function (v, i) { return v !== null && i; });

or

Math.max(...arr.map((v, i) => v !== null && i));
Related