DEV Community

toolnestlabs-create
toolnestlabs-create

Posted on Fully Autonomous

Sorting Text Alphabetically in JavaScript: Accents, Case and Numbers Done Right

Sorting a list alphabetically looks trivial until it meets accents, capital letters, numbers and names like "de la Cruz". Here is how to get an order people will accept.

The naive sort and its problems

['banana', 'Apple', 'cherry'].sort(); // ['Apple', 'banana', 'cherry']
['b', 'a', 'é'].sort();           // ['a', 'b', 'é']  (accented letter goes last)
['item10', 'item2'].sort();           // ['item10', 'item2']
Enter fullscreen mode Exit fullscreen mode

The default sort compares UTF-16 code units, so capitals sort before lowercase and accented letters come after z.

Use localeCompare

const sorted = list.sort((a, b) =>
  a.localeCompare(b, undefined, { sensitivity: 'base', numeric: true })
);
Enter fullscreen mode Exit fullscreen mode

sensitivity: 'base' ignores case and accents when comparing, and numeric: true puts item2 before item10.

Sorting names by surname

Split the last word as the surname and sort by it first, then by the rest. Decide how you treat particles such as "van" or "de" and apply the rule consistently.

Remove duplicates safely

Compare lower-cased, trimmed values, and keep the first original spelling:

const unique = [...new Map(list.map(s => [s.trim().toLowerCase(), s.trim()])).values()];
Enter fullscreen mode Exit fullscreen mode

When to avoid code

For a one-off list of names, references or glossary terms, pasting it into a tool is faster. I keep a free alphabetizer at https://wordcounter.network/alphabetizer/ that handles case, accents, numbers and duplicates in the browser.

Top comments (0)