Skip to content

re: Let's Count Some Sheep! VIEW POST


What you list as the "simplest way to solve this problem" is not actually the simplest solution. There is already a built-in JavaScript function that achieves this result:

const totalTrueValues = anyArray.filter(element => element === true).length;

If you want to technically meet the full requirement (which is to provide your own function that does this), then you just need to wrap the built-in JS solution in a function like:

function getTotalTrueValues(array) {
   return array.filter(element => element === true).length;

Wow, that's great Adam! I'm only 4 weeks into my studies, so I definitely have a lot more to learn. Thanks for posting this solution. I'll be using this!


I normally wouldn't make this kinda pedantic observation, but since you say you're "only 4 weeks into studies"...

Get rid of the var. You don't want to use that in "modern" JavaScript design. You should always, always, always use let or const.

It may feel right now like that's a semantic, rather useless, observation. But it's not just based on coding dogma. JavaScript has some particular, umm... headaches regarding this and the hoisting of var-declared variables into global scope. These headaches are solved by religiously sticking with let or constant.

The full description of why var is "problematic" is far longer than I care to type in this reply. But as you get further down your studies, it's a good thing to research.

Also, FWIW, the var keyword tends to cause headaches in other languages as well (e.g., C#).

function getTotalTrueValues(array) {
   return array.filter(Boolean).length;

You may use Boolean too

code of conduct - report abuse