Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array non undefined element count

I create an array with let arr = new Array(99999) but I don't fill it up to arr.length which is 99999, how can I know how much actual, non undefined elements do I have in this array?

Is there a better way than to look for the first undefined?

like image 523
shinzou Avatar asked Dec 10 '22 12:12

shinzou


1 Answers

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);
like image 88
Nina Scholz Avatar answered Dec 30 '22 09:12

Nina Scholz