Reputation: 2347
I'have the next array:
[null,null,null,null,null,null,2,10,29,43,45,40,54,39,13,1,null,null,null,null,null]
I need to know what is the first position in that array that is NOT null and the last that is NOT null too.
In this particular example, first will be 6 (counting 0 as position 1) and 15.
Thank you
Upvotes: 0
Views: 77
Reputation: 82594
Using non-standard array methods:
var arr = [null,null,null,null,null,null,2,10,29,43,45,40,54,39,13,1,null,null,null,null,null];
var mapped = arr.map(function (i) {
"use strict";
return i !== null;
});
var first = mapped.indexOf(true);
var second = mapped.lastIndexOf(true);
Both map and indexOf and lastIndexOf require IE9+ browsers or shims. However, they do look really cool.
Upvotes: 2
Reputation: 318498
var firstPos = -1, lastPos = -1;
for(var i = 0; i < arr.length; i++) {
if(arr[i] !== null) {
if(firstPos == -1) {
firstPos = i;
}
lastPos = i;
}
}
Upvotes: 3