Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting wrong values looping through array for a particular value in javascript

Tags:

javascript

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

like image 687
Opeyemi Odedeyi Avatar asked Nov 18 '25 15:11

Opeyemi Odedeyi


1 Answers

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.

like image 56
Michael M. Avatar answered Nov 21 '25 07:11

Michael M.