Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of "Defined" Array Elements

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?

like image 267
Erik Avatar asked Mar 28 '12 06:03

Erik


People also ask

How do you count elements in an array?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do you count the number of elements in an array in C++?

Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements. Print the result.

Which property is used to count elements of an array?

The length property sets or returns the number of elements in an array.


1 Answers

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.

like image 57
ZER0 Avatar answered Sep 29 '22 06:09

ZER0