The information below is generally useful, but for the problem listed on the OP list, Ninaβs answer is by far the best solution.
They are called sparse arrays, and this is one of the few situations where you can use for-in for an array.
Remember that arrays are objects in JavaScript, and array entries are name-based properties (array indexes) that match certain criteria . Therefore, we can use functions that allow us to discover the properties of an object in order to find indexes on your sparse array.
for-in example:
for (var n in theArray) { if (theArray.hasOwnProperty(n) && isArrayIndex(n)) {
This answer shows how you can determine that n is an array index, and not 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 is good enough for most of us will be
function isArrayIndex(n) { return !isNaN(parseInt(n, 10)); }
Similarly, you can use Object.keys ; since it only looks at its own enumerated properties, you do not need the hasOwnProperty check:
Object.keys(theArray).forEach(function(n) { if (isArrayIndex(n)) {
Please note that officially , not one of them is in any particular order, even in ES2015 ("ES6"). Therefore, in theory, you can see indices from a numerical order. In the real world, I have never seen even the vaguely modern JavaScript engine that returned array indexes from a system. They are not obliged, but everyone that I tried does.
So officially, you will need to get a complete 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);
This will give you undefined if the array is empty, or the min index if it is not. But if you want to make an assumption, you will get the keys in numerical order:
// Makes an assumption that may not be true var min = +Object.keys(theArray).filter(isArrayIndex)[0];
If you use a JavaScript engine that is fully updated, you can rely on the order returned by Object.getOwnPropertyNames , which required to list array indices in order.
var min = +Object.getOwnPropertyNames(theArray).filter(isArrayIndex)[0];