Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 122020  / 12 Years ago, wed, march 28, 2012, 12:00:00

Given following array:



var arr = [undefined, undefined, 2, 5, undefined, undefined];


I'd like to get the count of elements which are defined (i.e.: those which are not undefined). Other than looping through the array, is there a good way to do this?


More From » undefined

 Answers
120

In recent browser, you can use filter



var size = arr.filter(function(value) { return value !== undefined }).length;

console.log(size);


Another method, if the browser supports indexOf for arrays:



var size = arr.slice(0).sort().indexOf(undefined);


If for absurd you have one-digit-only elements in the array, you could use that dirty trick:



console.log(arr.join().length);


There are several methods you can use, but at the end we have to see if it's really worthy doing these instead of a loop.


[#86569] Monday, March 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;