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

↘锁芯ラ 提交于 2019-11-30 11:42:00

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

Array.prototype.filter() - the easiest one, in my opinion.

console.log([true,false,true,false,true].filter(v => v).length);

or even simplier:

console.log([true,false,true,false,true].filter(Boolean).length);

Array.prototype.forEach()

var myCounter = 0;

[true,false,true,false,true].forEach(v => v ? myCounter++ : v);

console.log(myCounter);

You're returning a++ when the value is true, which will always be zero. Post-increment happens after the value is retrieved. So on the first iteration, a is 0, and the value of a++ is also 0, even though a is incremented. Because a and b are parameters of the callback, it's a fresh a on each call.

Instead:

myCount = [false,false,true,false,true].reduce(function(a,b){
  return b?a+1:a;
},0);

You should use ++a instead a++ because you have to change the value of a suddenly. a variable will be incremented after its value is returned.

 myCount = [false,false,true,false,true].reduce(function(a,b){
      return b? ++a:a;
    },0);
alert("myCount ="+ myCount); 

I am not really sure about this, but a and b aren't numbers.

You shoud do something like :

//trying to count the number of true in an array
myCount = [false,false,true,false,true].reduce(function(a,b){
cpt = 0;
if(a) cpt++;
if(b) cpt++;
return cpt;
},0);
alert("myCount ="+ myCount);  // this is always 0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!