
Ask HN: Why does JavaScript sort() order numerical arrays alphabetically? - maest
As you may or may not know:<p><pre><code>    &gt;&gt;&gt; [100,11].sort()
    Array [ 100, 11 ]
</code></pre>
From the Moz dev docs[0]:<p>&quot;The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.&quot;<p>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.<p>I&#x27;ve looked around but could not find any discussions about _why_ this choice was made. Can anyone share any insight on this design decision?<p>On a more personal note, I have just wasted a considerable amount of time chasing a bug caused by incorrect usage of sort().<p>[0]: https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Reference&#x2F;Global_Objects&#x2F;Array&#x2F;sort
======
lhorie
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)`

