Coffeescript sorting is incorrect

Here is 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 here .

The result will be:

Why is this not right? 9,6,8,11,10,7,5,4,3,2,1

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

This is probably due to strings and numbers, but "+" forces the string to a number, and in any case, the result is not correct for even comparing strings. It just seems random.

+4
source share
1 answer

As @Keith commented , the problem is not with Coffeescript, but with the wrong use of the comparator function that Array::sortaccepts.

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 . .

+3

Source: https://habr.com/ru/post/1657937/


All Articles