-1
arr=[-37.507,-3.263,40.079,27.999,65.213,-55.552];
arr.sort();

and the result is

arr=[-3.263,-37.507,-55.552,27.999,40.079,65.213]

Can any one help me what logic that "sort()" function is doing? Please explain me why "arr.sort();" gives the above result.? And other questions doesn't have the exact answer which explains what i am getting here.

3
  • 1
    You can have a look here stackoverflow.com/questions/234683/… Commented Nov 26, 2014 at 7:33
  • @RajKumar Thank you, But by using this function i couldn't able to get correct sorted array, U could see that in my question . Please explain it. Commented Nov 26, 2014 at 7:39
  • re: "other questions doesn't have the exact answer"; yes they do. The accepted answer on this question says: "By default the sort method sorts elements alphabetically"; which is exactly the problem you have, and the description is exactly the same as the answer you accepted on this question. Commented Nov 27, 2014 at 20:33

3 Answers 3

3

array.sort sorts strings, if you want to sort numerically, you need a comparison-function:

array.sort(function(a, b){return a-b});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @MBaas, But you can see that the result is wrong which is in my question could you explain it please?
The results is correct, pls. check here: jsfiddle.net/evpt2wfr
0

The default sort function treats each item as a string. Lexicographic order is not the same as numerical order. For numerical sorting, do this:

arr.sort(function (a, b) { return a - b });

The argument to sort() is a function that returns a negative number only if a comes before b.

Comments

0

use this:

arr.sort(function(a, b) {
    if (a>b) return 1;
    if (a<b) return -1;
    if (a==b) return 0;
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.