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//);
}
});
}
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)
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))
const checkedState = [false, true, false, true, true]
const count = checkedState.filter((value) => value).length
// Cleaner way
const anotherCount = checkedState.filter(Boolean).length
console.log(count)
console.log(anotherCount)
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.