Invalid javascript array element is undefined
I create an array with let arr = new Array(99999)
, but I do not fill it up to arr.length
, which is 99999
, how can I know how many actual, non- undefined
elements I have in this array?
Is there a better way than looking for the first one undefined
?
You can use Array#forEach
that 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);
To filter out unsharp / dense elements, you can use a callback that returns for each element true
.
Perhaps this link helps a little to understand the mechanics of sparse array: JavaScript: sparse arrays and dense arrays .
let array = new Array(99999),
nonsparsed;
array[30] = undefined;
nonsparsed = array.filter(_ => true);
console.log(nonsparsed);
console.log(nonsparsed.length);
The fastest and easiest way to filter elements in an array is ... well ... use a function to .filter()
filter out only those elements that are valid (not undefined in your case) and then check the .length
result ...
function isValid(value) {
return value != undefined;
}
var arr = [12, undefined, "blabla", ,true, 44];
var filtered = arr.filter(isValid);
console.log(filtered); // [12, "blabla", true, 44]