Strange sorting results in javascripts

The SORT function in javascripts cannot return the correct answer in some situations.

I am using http://jsconsole.com to check some examples:

[2, 10].sort()[2, 10]
[3, 10].sort()[10, 3]
[9, 10].sort()[10, 9]
[10, 11].sort()[10, 11]

      

I tested it on windows xp, windows 2008 with firefox and chrome.

+3


source to share


2 answers


I think you are confusing Java with JavaScript, but they are completely different programming languages. I'm pretty sure the code is JavaScript.

Default sort function for JavaScript sorting by string value rather than integer value. You have to do the latter manually, but it's pretty simple:



[3,10].sort(function (a, b) { return a - b; });

      

+10


source


To be honest, I have no JS experience, but it seems to sort by String value. IE: 1 is a lower character than 9, so anything that starts with 1 (even 11811891) will be "less than" 9.



+1


source







All Articles