Invalid javascript array element is undefined
2 answers
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);
+6
source to share
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]
+4
source to share