Filter the non-null get the value of last one, if you need the index get the index from the value. But requires the values to be unique.
// Last non-null value
const lastNonNull = arr.filter(x => x).pop();
// Index of last non-null
const indexOfLastNonNull = arr.indexOf(lastNonNull);
--Edit(1)
You may want to use reduce
method of arrays, but before run reverse
to make sure the sequence is from last to first.
reduce
works pretty fine, the first initial value is null
then we check for result
which is the first initial value so we pass on cur
which is the first element of array, if it is truthy we return idx
which is the index of array, if not we return null
which will become the result
in the next loop.
arr.reduce((result, cur, idx) => (result ? result : (cur ? idx : null)), null)
--Edit(2)
Or you may reverse
the array and run indexOf
like this:
arr.indexOf(null);
For reversing once you run arr.reverse()
it'll reverse the content of array. No need to return anything.