Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange results of sort in javascripts

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.

like image 656
Bangyou Avatar asked Dec 06 '25 17:12

Bangyou


1 Answers

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; });
like image 184
Explosion Pills Avatar answered Dec 08 '25 05:12

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!