I have a function that is supposed to loop through an array and count the values in the array that are true. in the example below, I am expecting a value of 4, since the values 6, 3, 30, and 7 are all truthy values while 0 is false.
function countTruthy(arr) {
var arrayLength = arr.length;
var truthy = 0;
for (var i = 0; i < arrayLength; i++) {
if(arr[i] == true) {
truthy++
}
}
return console.log(truthy)
}
countTruthy([6, 3, 0, 30, 7])
But the code above doesn't work and I keep getting 0 instead
While all non-zero numbers are truthy, it is not equal to true. Only 1 is equal to true. To double-check this, just try running 60 == true in your console and it will return false, however, if you run if (60) console.log('hi') it will print 'hi'.
tl;dr: Truthy values are not necessarily equal to true.
To fix this, just check if the value is 0 instead. Like this:
function countTruthy(arr) {
return arr.filter(x => x != 0).length;
}
console.log(countTruthy([6, 3, 0, 30, 7]))
Also, your function can be drastically reduced with .filter(). Just filter out all the zero values then return the length of the resulting array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With