Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
amateur Avatar asked Aug 25 '10 23:08

amateur


3 Answers

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.

like image 126
Ben Zotto Avatar answered Sep 28 '22 02:09

Ben Zotto


The filter method works with sparse arrays.

var first = array.filter(x => true)[0];
like image 38
Jeff Sheldon Avatar answered Sep 28 '22 00:09

Jeff Sheldon


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.

like image 22
B Manders Avatar answered Sep 28 '22 00:09

B Manders