Skip to content

Instantly share code, notes, and snippets.

@saisandeepvaddi
Created February 3, 2020 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saisandeepvaddi/1b619bc6c72fe7a9e11dcbe26917d864 to your computer and use it in GitHub Desktop.
Save saisandeepvaddi/1b619bc6c72fe7a9e11dcbe26917d864 to your computer and use it in GitHub Desktop.
JS natural/numerical sort example.
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'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment