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?

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
amateur
  • 43,371
  • 65
  • 192
  • 320

7 Answers7

4

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.

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
  • 1
    This may be horribly inefficient depending on the lowest index. – Jasper Aug 25 '10 at 23:13
  • 1
    @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. – Ben Zotto Aug 25 '10 at 23:15
  • @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. – Jasper Aug 25 '10 at 23:42
4

The filter method works with sparse arrays.

var first = array.filter(x => true)[0];
aleclarson
  • 18,087
  • 14
  • 64
  • 91
Jeff Sheldon
  • 2,074
  • 1
  • 14
  • 23
  • 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`. – Ben Zotto Aug 25 '10 at 23:11
  • My mistake, edited for an alternative, rather than adding another answer that might mislead others. – Jeff Sheldon Aug 25 '10 at 23:54
  • @GeorgeJempty Probably because it used `filter` so I figured "close enough", but you're right. My edit was too drastic. – aleclarson Feb 21 '18 at 22:50
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.

B Manders
  • 31
  • 1
2

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
aleclarson
  • 18,087
  • 14
  • 64
  • 91
micmcg
  • 2,372
  • 18
  • 16
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.

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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?

Douglas
  • 36,802
  • 9
  • 76
  • 89