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

后端 未结 4 1517
傲寒
傲寒 2020-12-16 11:11

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\

4条回答
  •  伪装坚强ぢ
    2020-12-16 11:39

    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);

提交回复
热议问题