3

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

I use http://jsconsole.com to test 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.

Jeff Miller
  • 2,405
  • 1
  • 26
  • 41
Bangyou
  • 9,462
  • 16
  • 62
  • 94
  • possible duplicate of [How to sort number in javascript sort method](http://stackoverflow.com/questions/4576903/how-to-sort-number-in-javascript-sort-method) – Mike Samuel Feb 11 '13 at 05:41

2 Answers2

10

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

The default sort functionality for JavaScript sorts by string value, not integer value. You must do the latter manually, but it's pretty simple:

[3,10].sort(function (a, b) { return a - b; });
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

Honestly, I have no JS experience, but it appears it is sorting by String value. IE: 1 is a lower character than 9, so anything that starts with 1 (even 11811891) will be 'less' than 9.