Natural Sort With Numeric Order
Sort file names and labels naturally so item2 comes before item10, using Intl.Collator with a deterministic tie-break.
Code
export function createNaturalComparator(locale = "en", options = {}) {
const collator = new Intl.Collator(locale, {
numeric: true,
sensitivity: "base",
...options,
});
return (left, right) => {
const a = String(left);
const b = String(right);
return collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
};
}
export const naturalCompare = createNaturalComparator();
export function naturalSort(values, compare = naturalCompare) {
if (!Array.isArray(values)) throw new TypeError("values must be an array");
return [...values].sort(compare);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.