Skip to content

Instantly share code, notes, and snippets.

@AmyShackles
Last active December 22, 2020 23:24
Show Gist options
  • Save AmyShackles/924cd2f868e4e180dfed4b426c54e77c to your computer and use it in GitHub Desktop.
Save AmyShackles/924cd2f868e4e180dfed4b426c54e77c to your computer and use it in GitHub Desktop.
Natural/alphanumeric sort in JavaScript
let arr = ['1st', '2nd', '11th', '12th', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '13th'];
const collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
arr.sort(collator.compare); // ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th"]
// If working with objects:
let planes = [{Model: "AT301A", Make: "Air Tractor"}, {Model: "KR-2", Make: "Starke"}, {Model: "V", Make: "Culver"}, {Model: "J-35", Make: "Beech"}];
planes.sort((a, b) => collator.compare(a.Make, b.Make)); // [{"Model":"AT301A","Make":"Air Tractor"},{"Model":"J-35","Make":"Beech"},{"Model":"V","Make":"Culver"},{"Model":"KR-2","Make":"Starke"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment