43

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?

3
  • 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) Commented Aug 28, 2013 at 19:45
  • 1
    For reference: 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 Commented Aug 28, 2013 at 19:51
  • 1
    Generally, don't reference w3 schools as they can be incorrect for a wide range of things. Commented Oct 10, 2013 at 13:12

2 Answers 2

60

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.

Sign up to request clarification or add additional context in comments.

3 Comments

parenthesizes don't match.
@CrazyTrain - thanks for the edit. thought I was going blind there :)
Here's a shorter version if you're into that sort of thing: yourArray.sort( (a,b) => a-b )
6

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);

1 Comment

you should use array literal instead. [...], not new Array(...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.