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.
1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
LastIndexOf(Array, Object, Int32) Searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional Array that extends from the first element to the specified index.
To remove all undefined values from an array:Use the Array. filter() method to iterate over the array. Check if each value is not equal to undefined and return the result. The filter() method will return a new array that doesn't contain any undefined values.
Using the Array pop() Method The Array pop() method is the simplest method used to remove the last element in an array. The pop() method returns the removed element from the original array.
You could use a while
loop and iterate from the end.
var array = [{ foo: 0 }, null, null, { bar: 42 }, null],
index = array.length;
while (index-- && !array[index]);
console.log(index);
console.log(array[index]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With