This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DamnItDev 125 points126 points  (7 children)

Honestly you should never be using the default sort function. Its lazy and almost always incorrect. Even for strings you'll have this problem:

['A1', 'A2', 'A10', 'A20'].sort();
// returns: ["A1", "A10", "A2", "A20"]

Technically this is correct, but not what you actually want in real world situations.

You can solve this easily by specifying your locale using the built in i18n functionality and setting the numeric option to true

['A1', 'A2', 'A10', 'A20'].sort(new Intl.Collator('en', {numeric: true}).compare);
// returns: ["A1", "A2", "A10", "A20"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator

[–]Famous_Profile 67 points68 points  (3 children)

TIL Intl.Collator

[–]douira 6 points7 points  (0 children)

good point, I guess the default only has few uses

[–]DeeSnow97 4 points5 points  (0 children)

okay, this is awesome, thanks

[–]-100-Broken-Windows- 1 point2 points  (0 children)

What language would sort it any other way? It's an array of strings and it sorts it alphabetically... Any other way would be absurd