Better JavaScript string sorting with collators
Pop quiz: how do you sort an array of strings so that any numbers (stored as strings), are sorted in the correct order? That is, if you have:
const vals = ['1743', '596', '94', '337']
After sorting, the expected result is:
['94', '337', '596', '1743']
JavaScript's default array sorting method doesn't do what you need or expect. The reason is easy to find, and is the third sentence on the MDN page for Array.prototype.sort:
The default sort order is according to string Unicode code points.
For years and years, JS devs have been writing their own compare functions. It's just one of those things that you learn to do even though it feels like something that should be baked into the language.
I recently had to deal with sorting some arrays similar to the above example. In my internet travels, I came across Intl.Collator via StackOverflow.
Initially, I was skeptical and confused as to why something related to i18n would have this capability, but it works!
It's a little more code than calling .sort()
, but not much:
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base'
})
vals.sort(collator.compare)
Now vals
is in the expected order. No need to mess with various natural sort algorithm implementations, collator is in the language and well supported.