Dev Basics · 3 min read
Sorting Text: Alphabetical, Natural, and Locale-Aware Order
Sorting a list of lines sounds trivial until file10.txt lands before file2.txt, or Zebra before apple. Computers sort by character codes unless told otherwise.
Try it yourself with the related tool.
Sort and de-duplicate lines →Advertisement
Plain (lexicographic) order
A default sort compares strings character by character using their code values. Digits come before uppercase letters, which come before lowercase ones. So Zebra precedes apple, and 10 precedes 2 because the character 1 is smaller than 2.
Natural sort
Natural sort treats runs of digits as numbers, giving file1, file2, file10 — the order a human expects. In JavaScript, a.localeCompare(b, undefined, { numeric: true }) or an Intl.Collator with numeric: true does this.
Case, accents, and languages
Alphabetical order depends on language: in Swedish, ä sorts after z, while in German it sorts with a. Locale-aware comparison handles this and can ignore case and accents when asked. Use it for anything shown to people.
Duplicates and blank lines
Sorting puts identical lines next to each other, which makes de-duplication easy. Decide first whether Apple and apple count as the same, and trim trailing spaces — invisible whitespace is the usual reason a "duplicate" survives.
