> JavaScript sorts arrays by using a default comparator that runs .toString and compares unicode code point values (with safe handling around null/undefined).
Is there an explanation somewhere of how they decided on that as the default comparator? My first inclination would have been to use "<" as the default comparator. That would sort purely numeric arrays numerically, and purely string arrays lexically, leaving only the case of arrays that mix numerical and non-numerical elements needing the programmer to step in and give an explicit comparator.
Re:The Curious Case of JavaScript’s `sort`
by fenomas on Wednesday April 13, 2016 @11:18AM
(#11488892)
> There is no concept of a typed number array in JS
Note that nowadays there are indeed Int16Array, Float32Array, and so forth, and their sort methods work numerically like you'd expect.
Re:The Curious Case of JavaScript’s `sort`
by abc_lisper on Wednesday April 13, 2016 @11:15AM
(#11488859)
One of the many reasons why I keep away from JS - it deviates from the norm without good reason, in arbitrary places.
There is no concept of a typed number array in JS. There is just "Array", and an array's contents can be heterogenous.
Imagine the following:
The default comparator is one that can be run on any arbitrary array. It's up to you as a caller to specify that you'd like to sort by a different comparator.For a more detailed read, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...