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.

1

2 Answers 2

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; });
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.