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
  • 515
  • 3
  • 6
  • 12

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
  • 59,869
  • 19
  • 150
  • 156
9

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
  • 687,336
  • 108
  • 737
  • 1,005
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
  • 15,022
  • 3
  • 41
  • 74