Get the first element of a sparse JavaScript array

I have an array of objects in javascript. I am using jquery.

How to get the first element in an array? I cannot use the index of the array - since I assign the index of each element when I add objects to the array. So the indices arent 0, 1, 2, etc.

Just need to get the first element of an array?

+5
source share
8 answers

If you are not using sequentially numbered elements, you will have to go through until you press 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 equivalent stupid construct. This gives you the first element index, which you may or may not need.

-, , O (1), O (n) . , , , , -, .

+4

filter .

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

:

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

?

:

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

jquery.

+2

Object.keys(array)[0] ( String) .

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
+2

ES5 Array#some.

. true :

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

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

console.log(index, value);
Hide result
+1

, Underscore. , compact:

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

, , - , . , Array.push ?

0

, :

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

1245,31
2045,45

, , , , .

0

You can also use this reusable open source array — the first component that returns the first element of this array.

Examples:

first([1, 2, 3]) // => 1
first(['a', 'b', 'c']) // => 'a'
-1
source

All Articles