Home > Software design >  How do I count the number of truth values in array? [duplicate]
How do I count the number of truth values in array? [duplicate]

Time:09-23

I am struggling with some logic but I think I am close. Is there any way to get the number of truth values from an array of booleans?

  const checkedState = [true, false, true]

  function handleCourseProgress() {
    //for each value that is true in the array...
    checkedState.forEach((value) => {
      //if the value is true...
      if (value === true) {
        //count and total them up here....
        setCourseProgress(//return the count//);
      }
    });
  }

CodePudding user response:

const checkedState = [false, true, false, true, true]

const count = checkedState.filter((value) => value).length

console.log(count)

Basically filtering the array and looking for the truthy values and checking the length of the array will do the trick and after that you can call the setCourseProgress(count) with the right count value.

CodePudding user response:

You can use simple filter or reduce

Filter for the value you want and then count the length of the filtered:

const filterQuantity = checkedState.filter((x) => x === true).length;

Reduce will process each entry and determine if we need to increment if true:

const reduceQuantity = checkedState.reduce((previousValue, currentValue) => {
  return (currentValue) ? previousValue   1 : previousValue;
}, 0);

Snippet:

const checkedState = [true, false, true];

const filterQuantity = checkedState.filter((x) => x === true).length;

const reduceQuantity = checkedState.reduce((previousValue, currentValue) => {
  return (currentValue) ? previousValue   1 : previousValue;
}, 0);

console.info(filterQuantity, reduceQuantity);

CodePudding user response:

filter out the elements that are true, and return the length of that array.

const one = [false, true, true];
const two = [true, true, true];
const three = [false, false, false, false];

function trueElements(arr) {
  return arr.filter(b => b).length;
}

console.log(trueElements(one));
console.log(trueElements(two))
console.log(trueElements(three))

CodePudding user response:

Another way is [true, false, true].filter(x=>x).length

CodePudding user response:

The easiest way is with reduce. Here's the example.

const checkedState = [true, false, true]

const answer = checkedState.reduce((acc, val) => val ? acc   val : acc);

console.log(answer)

  • Related