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);
}Inside the snippet
Count the functions createNaturalComparator and naturalSort as the entire surface area of Natural Sort With Numeric Order.
When the guard condition holds, TypeError is thrown rather than a bogus value returned.
A fresh value is allocated for the result; the arguments stay untouched.
Putting it to use
The main signature reads export function createNaturalComparator(locale = "en", options = {})
Treat createNaturalComparator as the API: import it, and ignore the supporting code.
Core lines
return [...values].sort(compare);
return (left, right) => {
const a = String(left);
const b = String(right);
return collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
};
if (!Array.isArray(values)) throw new TypeError("values must be an array");
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `createNaturalComparator` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Does the code validate its input?
- The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `createNaturalComparator`, `naturalSort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.