最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript array non undefined element count - Stack Overflow

programmeradmin3浏览0评论

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?

Share Improve this question asked Apr 5, 2017 at 7:27 shinzoushinzou 6,22215 gold badges73 silver badges137 bronze badges 6
  • 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
 |  Show 1 more ment

2 Answers 2

Reset to default 10

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);

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]

发布评论

评论列表(0)

  1. 暂无评论