By displaying undefined x 2
, your array clearly indicates that it's a sparse one which means you don't have any undefined items. You just don't have the keys to hold items to start with.
OK you may have and wish to keep proper void 0
or undefined
items (in which case all of the above solutions will fail) or a numeric value 0
or null
object item (in which case the accepted answer will fail).
In order to convert a sparse array to dense form the most efficient method would be a for in
loop (or Object.keys()
).
So for sparse array looping it's best to use
var res = [],
a = [];
a[1] = "cars.jpg";
a[5] = null;
a[999999] = "beauty.jpg";
// [undefined × 1, "cars.jpg", undefined × 3, null, undefined × 999993, "beauty.jpg"]
function dense(a){
var r = [];
for (i in a) r.push(a[i]);
return r;
}
console.time("test");
res = dense(a);
console.timeEnd("test");
console.log(res);
Now lets compare the above code with an elegant filtering solution;
var res = [],
a = [];
a[1] = "cars.jpg";
a[5] = null;
a[999999] = "beauty.jpg";
// [undefined × 1, "cars.jpg", undefined × 3, null, undefined × 999993, "beauty.jpg"]
console.time("test");
res = a.filter(Boolean);
console.timeEnd("test");
console.log(res);
So as you see null
is disappeared and it is slower since it checks all non existing keys. However with for in
loop keeping the falsey values or not is totally under your control.