6

I can't seem to figure this one out.

var arr = [2.62, 111.05, 1.05]
arr.sort(); 

This returns [1.05, 111.05, 2.62], but I'm expecting [1.05, 2.62, 111.05].

How can this be achieved? I've read a bit about writing a custom sort to split the "decimal" but haven't managed to have any success.

zoosrc
  • 505
  • 2
  • 6
  • 11

3 Answers3

16

By default sorting is alphabetically. You need to pass a function to the sort method

arr.sort(function(a, b){return a-b;});
styvane
  • 55,207
  • 16
  • 142
  • 150
8

The sort method compares the items as strings by default. You can specify a comparer function to make the comparison any way you like. This will compare the items as numbers:

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

Note: All numbers in Javascript a double precision floating point numbers, even if they happen to contain an integer value, so integer values and decimal values are not treated differently.

Guffa
  • 666,277
  • 106
  • 705
  • 986
2

This is the normal behavior for Array.sort() when it isn't given a comparator function. Try this:

var arr = [2.62, 111.05, 1.05];
arr.sort(function(a,b) { return a-b; });

From MDN:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

jdphenix
  • 14,226
  • 3
  • 39
  • 70