Languages

JavaScript - count number of true elements in array of boolean values

0 points
Asked by:
Aran-Busby
592

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
Answered by:
Aran-Busby
592

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

  1. JavaScript - count occurrences of array elements

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Boolean() constructor - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join