You know the drill:
[1,2,3,10,11,20,23].sort() // [1, 10, 11, 2, 20, 23, 3]
We all know it should be "[1,2,3,10,11,20,23]" instead, right?
You know the drill:
[1,2,3,10,11,20,23].sort() // [1, 10, 11, 2, 20, 23, 3]
We all know it should be "[1,2,3,10,11,20,23]" instead, right?
The default semantics of Array.prototype.sort
can not be changed for existing inputs, as this would break the web.
Note: TypedArrays thankfully don't have this issue: TypedArray.prototype.sort() - JavaScript | MDN
The most likely 'fix' here is if there was perhaps a convenient sorting function available: Builtin Ord / Compare method for primitives
Additionally, "sort numerically" isn't any more obvious a default choice than "sort lexicographically" - if anything, the comparator should simply be required, but of course it's too late for that kind of change.
All this is true but also we should add Number.compare
so you could at least array.sort(Number.compare)
instead of having to remember the order for the comparator.
(Oh, which I see @aclaymore already mentioned, whoops. Anyway I agree.)
We "sort of" already have that, in the form of new Intl.Collator(undefined, { numeric: true }).compare
. Downside is it works for natural numbers only, and works on strings. Upside is that it can work with arbitrarily large numbers.
BTW, should we have BigInt.compare
too, then? Also, would that work in ascending or descending order?
@jaroslav.tavgen Please avoid using slogans like "Make # great again". Especially when you actually mean # has never been "great" in the first place...
BTW, should we have
BigInt.compare
too, then?
Yup.
Also, would that work in ascending or descending order?
Ascending. This is ~universal across all languages and libraries.
See also this thread about comparator reversal and composition: Proposal idea: descending sort - #9 by tabatkins.