40

I have an array of float point numbers:

[ 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ]

After running sort() on the array I get this:

[ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ]

Notice how 5.8... is bigger than 49.6... for JavaScript (Node). Why is that?

How can I correctly sort this numbers?

jviotti
  • 17,881
  • 26
  • 89
  • 148
  • 1
    Use `arr.sort(function (a, b) { return a-b; });`. As it stands, the values are being sorted alphabetically. "2" comes before "4", which comes before "5", which comes before "8" (the comparison is the first "letter" of each number...until they match, then it compares the next letter, and so on) – Ian Aug 28 '13 at 19:45
  • 1
    For reference: http://www.w3schools.com/jsref/jsref_sort.asp. By default javascript's array sort method sorts alphabetically and ascending. Hence, why you pass in the sort method provided by @Ian – Suvi Vignarajah Aug 28 '13 at 19:51
  • 1
    Generally, don't reference w3 schools as they can be incorrect for a wide range of things. – jtromans Oct 10 '13 at 13:12

2 Answers2

56

Pass in a sort function:

[….].sort(function(a,b) { return a - b;});

results:

[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049] 

From MDN:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order.

dc5
  • 12,341
  • 2
  • 35
  • 47
5

The built in JS sort function treats everything as strings. Try making your own:

var numbers = new Array ( 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 );

function sortFloat(a,b) { return a - b; }

numbers.sort(sortFloat);
Matt Pavelle
  • 819
  • 5
  • 8