Comment

Comment by PaulJulius

The new implementation is still wrong, according to the specification.

Array.prototype.sort does not sort an array of numbers as expected. In JavaScript, [2, 10].sort() results in the array [10, 2].

As MDN points out, "The default sort order is according to string Unicode code points... If [compareFn is] omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element." [0] It has an example showing off the unintuitive behavior right at the top of the page.

This behavior is intended per the original ECMAScript specification[1, pg. 68]:

  When the SortCompare operator is called with two arguments 
  x and y, the following steps are taken:
  1. If x and y are both undefined, return +0.
  2. If x is undefined, return 1.
  3. If y is undefined, return −1.
  4. If the argument comparefn was not provided in the call 
     to sort, go to step 7.
  5. Call comparefn with arguments x and y.
  6. Return Result(5).
  7. Call ToString(x).
  8. Call ToString(y).
  9. If Result(7) < Result(8), return −1.
  10. If Result(7) > Result(8), return 1.
  11. Return +0.
The key points are items 4, 7 and 8.

[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

[1] http://www.ecma-international.org/publications/files/ECMA-ST...

parent PaulJulius 9 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton