Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

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.

share|improve this question

marked as duplicate by GitaarLAB, georg javascript Nov 26 '14 at 8:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
You can have a look here stackoverflow.com/questions/234683/… – Raj Kumar Nov 26 '14 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. – Prabhu Vignesh Rajagopal Nov 26 '14 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. – Carpetsmoker Nov 27 '14 at 20:33
up vote 3 down vote accepted

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

array.sort(function(a, b){return a-b});
share|improve this answer
    
Thank you @MBaas, But you can see that the result is wrong which is in my question could you explain it please? – Prabhu Vignesh Rajagopal Nov 26 '14 at 7:37
    
The results is correct, pls. check here: jsfiddle.net/evpt2wfr – MBaas Nov 26 '14 at 7:41

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.

share|improve this answer

use this:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.