EN
JavaScript - count number of true elements in array of boolean values
1
answers
0
points
How can I count number of true elements in array of boolean values?
My array:
var array = [true, false, true, true];
I need a function that will count all true elements and return 3 in this case.
1 answer
0
points
You can use filter() method to get array of all the truthy values from the original array, then the length property of the filtered array will be the number of truthy values.
Practical examples
Example 1
// ONLINE-RUNNER:browser;
const array = [true, false, true, true];
const result = array.filter(Boolean).length;
console.log(result); // 3
Example 2
// ONLINE-RUNNER:browser;
var array = [true, false, true, true];
const result = array.filter((element) => element).length;
console.log(result); // 3
See also
References
0 comments
Add comment