Javascript array non undefined element count

You could use Array#forEach, which skips sparse elements.

let array = new Array(99999),
    count = 0;

array[30] = undefined;

array.forEach(_ => count++);

console.log(count);

The same with Array#reduce

let array = new Array(99999),
    count = 0;

array[30] = undefined;

count = array.reduce(c => c + 1, 0);

console.log(count);

For filtering non sparse/dense elements, you could use a callback which returns for every element true.

Maybe this link helps a bit to understand the mechanic of a sparse array: JavaScript: sparse arrays vs. dense arrays.

let array = new Array(99999),
    nonsparsed;

array[30] = undefined;

nonsparsed = array.filter(_ => true);

console.log(nonsparsed);
console.log(nonsparsed.length);

Leave a Comment