azelix azelix - 5 months ago 23
jQuery Question

Get first element in array with index not starting from 0

I'm using a javascript library which returns arrays not starting from zero like starting from 26 or 1500, what i want to do is a method to get the first element in that array regardless of the index number starting with 0 or any other number.

Are they any method to do this in javascript ?

Answer

The information below is generally useful, but for the problem the OP listed, Nina's answer is by far a better solution.


Those are called sparse arrays and they're one of the few situations where you may want to use for-in on an array.

Remember that arrays are objects in JavaScript, and array entries are properties keyed by names (array indexes) that meet certain criteria. So we can use the features that let us discover the properties on an object to find the indexes on your sparse array.

for-in example:

for (var n in theArray) {
    if (theArray.hasOwnProperty(n) && isArrayIndex(n)) {
        // Use theArray[n]
    }
}

This answer shows how you can determine that n is an array index as opposed to being some other property. A very technical definition would be

function isArrayIndex(n) {
    return /^0$|^[1-9]\d*$/.test(n) &&
           n <= 4294967294;
}

...but a definition that's good enough for most of us would be

function isArrayIndex(n) {
    return !isNaN(parseInt(n, 10));
}

Similarly, you can use Object.keys; since it only looks at own enumerable properties, you don't need the hasOwnProperty check:

Object.keys(theArray).forEach(function(n) {
    if (isArrayIndex(n)) {
        // ...
    }
});

Note that officially, neither of those is in any particular order, not even in ES2015 ("ES6"). So in theory, you could see the indexes out of numeric order. In the real world, I've never seen an even vaguely-modern JavaScript engine that returned array indexes out of order. They're not required to, but every one I've tried does.

So officially, you would need to get a full list and then find the minimum value in it:

var min = Object.keys(theArray).reduce(function(min, n) {
    var i = parseInt(n, 10);
    return isNaN(i) || (min !== undefined && min > i) ? min : i;
}, undefined);

That'll given you undefined if the array is empty, or the min index if it isn't. But if you want to make the assumption you'll get the keys in numeric order:

// Makes an assumption that may not be true
var min = +Object.keys(theArray).filter(isArrayIndex)[0];

If you're using a JavaScript engine that's entirely up-to-date, you can rely on the order returned by Object.getOwnPropertyNames, which is required to list the array indexes in order.

var min = +Object.getOwnPropertyNames(theArray).filter(isArrayIndex)[0];