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
?
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
?
- Is there a better way than to look for this we would need your code to pare if our approach is better or worse. Also a user with your rep should know the importance of code – Rajesh Commented Apr 5, 2017 at 7:30
-
My approach is
arr.indexOf("undefined")
@Rajesh – shinzou Commented Apr 5, 2017 at 7:31 - Please share it in question as that would help everyone who reads your question – Rajesh Commented Apr 5, 2017 at 7:32
- It doesn't actually work though and I hoped to avoid having to loop through the array. @Rajesh – shinzou Commented Apr 5, 2017 at 7:33
- 1 Possible duplicate of Count of "Defined" Array Elements – Slartibartfast Commented Apr 5, 2017 at 7:36
2 Answers
Reset to default 10You 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);
The fastest & simplest way to filter items in an array is to... well... use the .filter()
function, to filter out only the elements that are valid (non undefined in your case), and then check the .length
of the 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]