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
?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With