Johanovski
Johanovski

Reputation: 235

False positives while comparing integers in Javascript

I'm facing a really strange problem comparing integer in Javascript. I have an array of numbers and I want to check if the current number in a loop is smaller than the previous one. To do so, I save the "current" number as "previous", so I can check them in the next loop. The function runs as expected, EXCEPT every time the current and the previous number have a different number of digits: in this case, the code doesn't see the actually smaller number as being smaller than the previous one.

For example:

111 < 120 ? ---> YES!

106 < 111 ? ---> YES!

98 < 106  ? ---> NO!

76 < 98   ? ---> YES!

5 < 76    ? ---> NO!

I'm unable to find anything strange in the code I'm using, as it is quite simple:

for(var j=0;j<arrScores.length;j++)
{
    if(arrScores[j][0] < scoreAnt)
    {
        console.log("Smaller!");
    }

    scoreAnt = arrScores[j][0];
}

I've tried using parseInt() in both values, but nothing changes... Checking the length of both numbers using scoreAnt.toString().length returns a length of 1, no matter which number it is (100, 34 or 156798), and the same for arrScores[j][0]. I've also logged the whole thing to check that the numbers are the expected ones, and they are (the numbers used in the example are some of the ones I'm using)...

Any clue on what can be happening? I'm really lost with this, becuase it makes no sense for me...

Thanks in advance for your time and effort! :)

Upvotes: 0

Views: 66

Answers (2)

Johanovski
Johanovski

Reputation: 235

Well, don't even know why, but after changing something relating the CORS of the server where these numbers came from (but not modifying the numbers at all), the comparison seems to work as expected... Have no clue about what might have changed! :S However, now it works correctly...

Upvotes: 0

Mr Lister
Mr Lister

Reputation: 46589

You always do scoreAnt = arrScores[j][0]; in the loop; but you should only do that if arrScores[j] is smaller; i.e. inside the inner curly braces.

for(var j=0;j<arrScores.length;j++)
{
    if(arrScores[j][0] < scoreAnt)
    {
        console.log("Smaller!");
        scoreAnt = arrScores[j][0];
    }
}

Upvotes: 1

Related Questions