0

Newbie here. Trying to write a function that accepts an array of strings and counts the number of strings that can be converted to a number. example: ['1', 'h','3','l','p','7'] should return 3.

function countNumbers(arr) {
  for (let i of arr) {
    let num = parseInt(i);
    let total = 0
    if (num >= 0) {
      total++;
      return total
    }
  }
}

console.log(countNumbers(['1', 'h','3','l','p','7']));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
izzy
  • 1
  • 2
    To help you learn, instead of the complete solution, here's a hint: The [isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN) function helps you determine if a value can be converted to a number. – bzyr Apr 24 '22 at 07:37
  • 1
    Why your code returns 1: If you return from the for-loop, you stop the iteration, and your function returns immediately. As for your `parseInt` and `num >= 0` check, what about negative numbers? – bzyr Apr 24 '22 at 07:54
  • 1
    Thanks SO MUCH for your help! Originally I had it written as if(parseInt(i) !==NaN) but that wasn't working. I understand why now after reading about the isNaN function. As for the return inside the for loop, I've moved the return and the total variable outside the for loop. – izzy Apr 24 '22 at 08:20

0 Answers0