Johntyb
Johntyb

Reputation: 105

How would I determine the index of the last item in javascript array with a value > 0

As my question states how would I determine the index of the last item in JavaScript array with a value > 0

So if myarray = [12, 35, 56, 0, 42, 0]

How would I find the index of the last positive integer in this array? i.e in this instance the answer would be 4 (no. 42).

Upvotes: 1

Views: 133

Answers (6)

odinho - Velmont
odinho - Velmont

Reputation: 21506

You can get the reverse index with .reverse() and .findIndex, then do some basic arithmetic to flip it:

> myarray = [12, 35, 56, 0, 42, 0]
> var ridx = myarray.slice().reverse().findIndex(n => 0 < n)
1
> var idx = myarray.length - 1 - ridx
4

Upvotes: 0

A. Magalh&#227;es
A. Magalh&#227;es

Reputation: 1516

Try this solution:

var myarray = [12, 35, 56, 0, 42, 0], index;
$.each(myarray,function(idx,el){
    if(el > 0){ 
        index = idx;
    }
});
alert('Index:'+index+', value:'+myarray[index]);

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Hope this helps:

for(var i=myarray.length-1; i>=0;i--){
    if(myarray[i] > 0){
       alert(i);
       break;
  }
}
if(i<0)
alert(i);

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72857

Try this:

var array = [12, 35, 56, 0, 42, 0];
function getLastNotZero(array){
    var t = 0, i = array.length-1;
    while(t <= 0 && i >= 0){
        t = array[--i];
    }
    return i-1;
}
getLastNotZero(array);
//Returns 4

Upvotes: 0

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

this should do it:

var myarray = [12, 35, 56, 0, 42, 0];
var found = {};
found.value = 0;
found.index = 0;
var j = myarray.length;
for (j; j>0; j--) {
    if (myarray[j] > 0) {
        found.value = myarray[j];
        found.index = j;
        break;
    }
}
alert(found.index);

EDIT: note the above would not clarify the 0 index or none so:

found.value = undefined;
found.index = undefined;
var j = myarray.length;
for (j; j>0; j--) {
    if (myarray[j] > 0) {
        found.value = myarray[j];
        found.index = j;
        break;
    }
}
alert(found.index);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074238

There's no shortcut, just loop backward through the array from length - 1 to 0 (inclusive) and stop at the first >0 entry.

Upvotes: 5

Related Questions