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
3 Answers 3
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.
Comments
Whether a value is "truthy" (like 6 is truthy, but not really equal to true) has a meaning that goes beyond just numbers, and besides 0, also NaN is a falsy value in the numeric data type domain. To accurately count truthy values, you can use Boolean as call back, like this:
const countTruthy = arr => arr.filter(Boolean).length;
console.log(countTruthy([6, 3, 0, 30, 7])); // 4
console.log(countTruthy([6, 3, NaN, 30, 7])); // 4
console.log(countTruthy(["a", "b", "", "c", "d"])); // 4
console.log(countTruthy([true, true, false, true, true])); // 4
console.log(countTruthy([{}, undefined, null])); // 1
Comments
As @Michael mentioned above, 0 is false but not all truthy values are equal to true. With that said, here is how you can achieve the desired result.
function countTruthy(arr) {
var arrayLength = arr.length;
var truthy = 0;
for (var i = 0; i < arrayLength; i++) {
if (arr[i]) {
truthy += 1;
}
}
return console.log(truthy);
}
countTruthy([6, 3, 0, 30, 7])