开发者

Get first element of a sparse JavaScript array

I have an array of objects in javascript. I use jquery.

How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.

Just need 开发者_开发问答to get the first element of the array?


If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:

var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
    firstIndex++;
}
if (firstIndex < myarray.length) {
    var firstElement = myarray[firstIndex];
} else {
    // no elements.
}

or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.

If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.


The filter method works with sparse arrays.

var first = array.filter(x => true)[0];


Have you considered:

function getFirstIndex(array){
    var result;
    if(array instanceof Array){
        for(var i in array){
            result = i;
            break;
        }
    } else {
        return null;
    }
    return result;
}

?

And as a way to get the last element in the array:

function getLastIndex(array){
    var result;
    if(array instanceof Array){
            result = array.push("");
            array.pop;
        }
    } else {
        return null;
    }
    return result;
}

Neither of these uses jquery.


Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.

var array = [];
array[2] = true;
array[5] = undefined;

var keys = Object.keys(array);            // => ["2", "5"]
var first = Number(keys[0]);              // => 2
var last = Number(keys[keys.length - 1]); // => 5


I was also facing a similar problem and was surprised that no one has considered the following:

 var testArray = [];
 testArray [1245]= 31;
 testArray[2045] = 45;
 for(index in testArray){
    console.log(index+','+testArray[index])
 }

The above will produce

1245,31
2045,45

If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.


This is a proposal with ES5 method with Array#some.

The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:

var a = [, , 22, 33],
    value,
    index;

a.some(function (v, i) {
    value = v;
    index = i;
    return true;
});

console.log(index, value);


If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:

var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];

However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜