Rob Rob - 11 months ago 79
CoffeeScript Question

coffeescript sorting not right

Here's my script:

alert("why isn't this sorted right? #{["6","7","2","11","10","9","4","5","3","8","1"].sort
(a,b) -> +a < +b }")

You can try running it here.

The result will be:

why isn't this sorted right? 9,6,8,11,10,7,5,4,3,2,1

My question is, why? I would expect the answer to be 11, 10, 9, 8, ....

It probably has something to do with strings vs numbers, but the "+" coerces the string to a number, and anyway, the result isn't a correct sort for even a string comparision. It just seems .. random.

Answer Source

As Keith commented, the issue isn't with Coffeescript, but with a misuse of the comparator function, which Array::sort accepts.

  "In order to work, a comparator must return -1, 1 or 0 #{
      (a,b, c = +a, d = +b) ->
        if c < d then -1
        else if c > d then 1
        else 0

Array.sort documentation. Run it here.