Ryul
Ryul

Reputation: 139

Count number of True/False without `.reduce()`,`.filter()` `forEach()`

 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

Upvotes: 2

Views: 239

Answers (3)

Jackkobec
Jackkobec

Reputation: 6745

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

Upvotes: 1

jo_va
jo_va

Reputation: 13983

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([]));

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370999

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

Upvotes: 1

Related Questions