Issue
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//);
}
});
}
Solution
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.
Answered By – jean182
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0