Syntax
const collator = new Intl.Collator("en", { numeric: true });
items.sort(collator.compare);Examples
Locale-aware Sorting with Intl.Collator: working example
Run this standalone example in a modern browser console unless another environment is specified. Expected result: The sorted copy logs file1,file2,file10; the original remains file10,file2,file1.
const files = ["file10", "file2", "file1"];
const collator = new Intl.Collator("en", { numeric: true });
console.log([...files].sort(collator.compare).join(","));
console.log(files.join(","));- Expected result: The sorted copy logs file1,file2,file10; the original remains file10,file2,file1.
- numeric compares digit runs numerically instead of purely lexicographically.
- The original is copied because sort mutates its receiver.
Best practices
- Reuse a collator when sorting many values.
- Do not assume compare returns exactly -1 or 1; only its sign is specified.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification