Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 371
Zenoo Avatar asked May 22 '17 12:05

Zenoo


People also ask

How do we get the index of a last element of an array?

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.

What is the last index of the array?

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.

How do you filter an undefined array?

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.

How do I get an array without the last element?

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.


2 Answers

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]);
like image 173
Nina Scholz Avatar answered Oct 10 '22 14:10

Nina Scholz


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.

like image 4
PRAISER Avatar answered Oct 10 '22 13:10

PRAISER