0

my code is like that.. i m using isNaN() but problem is still valid

function numberSearch (str) {
    let sum = 0;
    let strCount = 0;
    
    if(str === "") {
        return 0;
    };
  
    for(let i = 0 ; i < str.length; i++) {
        if (isNaN(Number(str[i]))) {
            strCount = strCount + 1   // if it's true, +1
        }
        sum = sum + Number(str[i])
    } 
    return Math.round(sum/strCount);
}
let output = numberSearch('Hello6 ');
console.log(output); // --> 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1

How can I count the number and calculate it?

I'm using isNaN(), but when i using debugger sum is 'NaN' I cant treat well.. i cant understand well..

Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
Loolii
  • 397
  • 3
  • 9
  • 1
    `NaN !== NaN` will evaluate to `true`, because a "NaN" is not equal to any value, including itself. You need to use `isNaN()` to check if a given value is NaN. – Joachim Sauer Feb 16 '21 at 18:08

1 Answers1

2

Scroll for answer to edited question.

NaN === NaN

will be false, there is a good explanation given here.

Try using isNaN() for your check instead of comparison.

Edit: As far I understood you, you want to get a rounded average of the numbers found within the string. The if check is modified accordingly -- it has to increase count and sum, if there is a number being checked:

function numberSearch (str) {
    let sum = 0;
    let count = 0;
  
    if (str === '') {
        return 0;
    };
    
    for (let i = 0 ; i < str.length ; i++) {
        // if character is not empty and is a number,
        // increase count and sum
        if (str[i] !== ' ' && !isNaN(Number(str[i]))) {
            count++;
            sum = sum + Number(str[i]);
        }
    }
 
    return Math.round(sum/count);
}

let output = numberSearch('Hello6 ');
console.log(output); // 6 now, 6 / 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 6 now, 17 / 3
Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22