2
 var x = [true,false,true,false]

Is there a way to tell how many "True" are within an array? But without using .reduce(),.filter() forEach():

How to get the count of boolean value (if it is true) in array of objects

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

Ryul
  • 139
  • 12

3 Answers3

1

If there can only be true/false elements, I guess you could .join and then check how many trues there are in the string with a regular expression:

const getTrueCount = array => (array.join().match(/true/g) || []).length;
console.log(getTrueCount([true,false,true,false]));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

The simplest solution is to use casting boolean to number (true => 1, false => 0). Unary + before operand is used for this action:

const array = [true, false, true, false];

function getTrueCount(array) {
    let trueCount = 0;
    for (let i = 0; i < array.length; i++) {
        trueCount += +(array[i]);
    }

    return trueCount;
}
piet.t
  • 11,718
  • 21
  • 43
  • 52
Jackkobec
  • 5,889
  • 34
  • 34
0

A functional approach would be to do it recursively, this uses no loops and no array methods:

const countTrue = ([x, ...r]) => (+x || 0) + (r.length ? countTrue(r) : 0);

console.log(countTrue([true,false,true,false]));
console.log(countTrue([false,false,true,false]));
console.log(countTrue([false,false,false,false]));
console.log(countTrue([]));
jo_va
  • 13,504
  • 3
  • 23
  • 47