Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of true members in an array of boolean values

New to javascript and I'm having trouble counting the number of trues in an array of boolean values. I'm trying to use the reduce() function. Can someone tell me what I'm doing wrong?

   //trying to count the number of true in an array     myCount = [false,false,true,false,true].reduce(function(a,b){       return b?a++:a;     },0);     alert("myCount ="+ myCount);  // this is always 0 
like image 747
gitmole Avatar asked Feb 18 '17 15:02

gitmole


People also ask

How do you count Boolean values in Java?

The countTrue() method of Booleans Class in Guava Library is used to count the number of values that are true in the specified boolean values passed as the parameter. Parameters: This method accepts the boolean values among which the true values are to be count.

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

Python len() method enables us to find the total number of elements in the array/object. That is, it returns the count of the elements in the array/object.


1 Answers

Seems like your problem is solved already, but there are plenty of easier methods to do it.

Excellent one:

.filter(Boolean); // will keep every truthy value in an array 

const arr = [true, false, true, false, true]; const count = arr.filter(Boolean).length;  console.log(count);

Good one:

const arr = [true, false, true, false, true]; const count = arr.filter((value) => value).length;  console.log(count);

Average alternative:

let myCounter = 0;  [true, false, true, false, true].forEach(v => v ? myCounter++ : v);  console.log(myCounter);
like image 74
kind user Avatar answered Oct 07 '22 21:10

kind user