HACKER Q&A
📣 maest

Why does JavaScript sort() order numerical arrays alphabetically?


As you may or may not know:

    >>> [100,11].sort()
    Array [ 100, 11 ]
From the Moz dev docs[0]:

"The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values."

I find this: 1. surprising: I am not aware of any other languages that do this. 2. inefficient: sort() converts everything into a string first.

I've looked around but could not find any discussions about _why_ this choice was made. Can anyone share any insight on this design decision?

On a more personal note, I have just wasted a considerable amount of time chasing a bug caused by incorrect usage of sort().

[0]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


  👤 lhorie Accepted Answer ✓
Because that's a fairly reasonable way of handling array items of unknown type. For example: what should `['1', 2]` do? What about `['1e2', 2]`? `['1_000', 2]`? `['0x3', 2]`? `[true, 2]`, etc.

For numerical sort, pass an callback specifying a numerical sort: `array.sort((a, b) => a - b)`