0
var sor = ['11', '0', '22', '33'];
for(var i = 0 ; i <=10;i++){
     sor.push('11222111111113332323231111'+i);
}

function sortnum(num1,num2){
  return num2-num1;
}
sor.sort(sortnum);

$.each(sor,function(index,val){
     $('div').append(val+'<br/>');
}); 

the result for firefox as below:

122111111111333232323111110
12211111111133323232311113
12211111111133323232311119
12211111111133323232311118
12211111111133323232311110
12211111111133323232311111
12211111111133323232311112
12211111111133323232311117
12211111111133323232311114
12211111111133323232311115
12211111111133323232311116
33
22
11
0

but what i expect is:

122111111111333232323111110

12211111111133323232311119
12211111111133323232311118
12211111111133323232311117
12211111111133323232311116
12211111111133323232311115
12211111111133323232311114
12211111111133323232311113
12211111111133323232311112
12211111111133323232311111
12211111111133323232311110
33
22
11
0
Brad
  • 159,648
  • 54
  • 349
  • 530
terry
  • 301
  • 3
  • 17

1 Answers1

2

By subtracting the arguments, they will implicitly be converted into numbers. However, a number like 122111111111333232323111110 is just out of range, the biggest integer Javascript can handle (natively) is 9007199254740992 (see this).

This causes the calculation to fail.

If you want to compare these stringified numbers anyway, you need to compare the strings with a custom comparison instead of relying on built-in mathematics. It could look something like this:

function compare(a, b) {
    if(a.length !== b.length) {
        return b.length - a.length;
    }

    for(var i = 0; i < a.length; i++) {
        if(a[i] !== b[i]) {
            return b[i] - a[i];
        }
    }

    return 0;
}

Check out this fiddle. However this will only work for positive integers.

Community
  • 1
  • 1
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
  • it also doesn't work for numbers with leading zeroes, for example `001234`. But otherwise it is fine. – Roland Illig Nov 17 '13 at 17:27
  • 1
    @RolandIllig Why shouldn't it work for leading zeros? In any case, I don't consider leading zeros as "correct, normal decimal notation". – Ingo Bürk Nov 17 '13 at 17:39