Count of "Defined" Array Elements

Erik picture Erik · Mar 28, 2012 · Viewed 121k times · Source

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?

Answer

ZER0 picture ZER0 · Mar 28, 2012

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.