最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Get first element of a sparse JavaScript array - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited May 4, 2011 at 21:18 Ateş Göral 140k27 gold badges141 silver badges191 bronze badges asked Aug 25, 2010 at 23:03 amateuramateur 44.6k71 gold badges196 silver badges324 bronze badges 1
  • 1 What are you using as the array index then? – Tim Down Commented Aug 25, 2010 at 23:07
Add a comment  | 

7 Answers 7

Reset to default 5

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)

  1. 暂无评论