JavaScript

Sort human-readable text with Intl.Collator

Use Intl.Collator when sorting names or filenames for people. A chosen locale and options make the intended text ordering clearer than relying on Unicode code-point comparisons.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const names = ["file10", "file2", "file1"];
const collator = new Intl.Collator("en", {numeric: true});
console.log(JSON.stringify(names.toSorted(collator.compare)));

How it works

The numeric option compares runs of digits as numbers, placing file2 before file10. Construct the collator once and reuse its compare function for a whole list rather than repeatedly building locale options inside a comparator.

Limits and mistakes

Locale-sensitive results can differ across locales and runtime internationalization data. Human-readable sorting is not a canonical byte order for signatures or deterministic cross-platform storage. Use an explicit machine ordering for those tasks.

Check the result

Expect file1, file2, file10. Add accented names and choose the locale your readers actually use before deciding that a particular alphabetical order is correct.

Sources

Reference documentation for the behavior used in this guide: