-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.

  • 1
    You can have a look here http://stackoverflow.com/questions/234683/javascript-array-sort-implementation – Raj Kumar Nov 26 '14 at 07: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 07:39
  • re: "other questions doesn't have the exact answer"; yes they do. The [accepted answer](http://stackoverflow.com/a/1063027/660921) 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. – Martin Tournoij Nov 27 '14 at 20:33

3 Answers3

3

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

array.sort(function(a, b){return a-b});
MBaas
  • 7,248
  • 6
  • 44
  • 61
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.

Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47
0

use this:

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