-
-
Save saisandeepvaddi/1b619bc6c72fe7a9e11dcbe26917d864 to your computer and use it in GitHub Desktop.
JS natural/numerical sort example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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