Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - count empty values in array

Given an array:

var arr = [1,,2,5,6,,4,5,6,,];

Count how many empty values is has: (length - length after removing the empty values)

var empties = arr.length - arr.filter(function(x){ return true }).length;

// return 3

or something like this

arr.empties = arr.length;
arr.forEach(function(x){ arr.empties--  });

// arr.empties returns 3

Is this the best way or am I missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on your comments to another answer, it looks like you're after the shortest method. Well, you might want to consider a variation of your own example:

var empties = arr.length - arr.filter(String).length;

All you're doing is passing a native function rather than an anonymous function, saving a few precious bytes. Any native constructor or function will do, as long as it doesn't return a boolean.


You need to be more specific about what you would consider the 'best way'. For instance, some methods will give better performance than others, some are more concise and some have better compatibility.

The solutions you mention in the post require browsers to be compatible with the ECMAScript 5th Edition specification, so they won't work in some older browsers (read: IE8 and lower).

The "best" all-round approach is a simple loop. It's not as concise as your methods, but it will no doubt be the fastest and most compatible:

var arr = [1,,2,5,6,,4,5,6,,], count = 0, i = arr.length;

while (i--) {
    if (typeof arr[i] === "undefined")
        count++;
}

This makes use of loop optimisations (using while and decrementing is faster than for).

Another approach would be to sort the array so that undefined items are all at the end and use a loop to iterate backwards:

var arr = [1,,2,5,6,,4,5,6,,], count = 0;
arr.sort();
while (typeof arr.pop() === "undefined") count++;

alert(count); 
//-> 3

This approach would modify the original array and remove those items which may not be what you want. However, it may be much faster on very large arrays.

Performance test suite
http://jsperf.com/count-undefined-array-elements


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...