Get first element of a sparse JavaScript array
Asked Answered
S

7

6

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?

Seafarer answered 25/8, 2010 at 23:3 Comment(1)
What are you using as the array index then?Aman
R
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.

Ricarda answered 25/8, 2010 at 23:5 Comment(3)
This may be horribly inefficient depending on the lowest index.Verity
@Jasper: Of course it may be; as noted, it's O(n) in the length of the array. But it's the best you're going to do given the data structure.Ricarda
@quixito: that would be O(n) in the first # array element, which can be higher than the number of elements in the array, but is lower than array.length as long as there is more than one element. However, since the specification do not require a certain array efficiency, it does not need to be such. Additionally, the fact that it is a sparse array actually makes that it is probably slower than that.Verity
M
4

The filter method works with sparse arrays.

var first = array.filter(x => true)[0];
Moresque answered 25/8, 2010 at 23:6 Comment(3)
-1. Incorrect; this does not answer the question. OP wants the first "valid" item, whatever index it is at (not necessarily zero). shift will only pull off whatever is at element 0, including undefined.Ricarda
My mistake, edited for an alternative, rather than adding another answer that might mislead others.Moresque
@GeorgeJempty Probably because it used filter so I figured "close enough", but you're right. My edit was too drastic.Ioannina
P
3

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.

Polaroid answered 4/5, 2011 at 19:58 Comment(0)
E
3

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
Eld answered 22/3, 2016 at 4:18 Comment(0)
H
1

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.

Horsecar answered 21/11, 2016 at 4:24 Comment(0)
R
1

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);
Rayner answered 1/12, 2016 at 18:26 Comment(0)
A
0

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?

Allo answered 25/8, 2010 at 23:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.