Natural sort in Javascript

Published:

Sorting strings naturally/numerically in Javascript is very simple. You just need to remember the existence of the Intl.Collator... which I keep forgetting...

You simply create one and use its compare function:

const collator = new Intl.Collator(undefined, {
  usage: 'sort',
  numeric: true,
})

const simple = ['a1', 'a12', 'a2']
simple.sort(collator.compare)
// => ['a1', 'a2', 'a12']

const objects = [{ id: 'a1' }, { id: 'a12' }, { id: 'a2' }]
const by = (key) => (a, b) => collator.compare(a[key], b[key])
objects.sort(by('id'))
// => [{id: 'a1'}, {id: 'a2'}, {id: 'a12'}]