Reputation: 4434
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.
Upvotes: 4
Views: 120
Reputation: 2109
As @Keith commented, the issue isn't with Coffeescript, but with a misuse of the comparator function, which Array::sort
accepts.
alert(
"In order to work, a comparator must return -1, 1 or 0 #{
["6","7","2","11","10","9","4","5","3","8","1"].sort(
(a, b) -> +b - +a
)}"
)
Array.prototoype.sort
documentation.
Run it here.
Upvotes: 2