Skip to content
jshacks.dev
Fundamentals

Sort strings naturally with Intl.Collator

Sort strings with numbers in them naturally with Intl.Collator, so file2 comes before file10, and compare how localeCompare treats case. Node.js 18.

2 min read
Summarize in AI

The default sort() puts file10 before file2, and so does localeCompare. Intl.Collator with numeric: true compares runs of digits as numbers instead, and the sorts below ran on Node.js 24.

JavaScript
const files = ['file10.txt', 'file2.txt', 'File1.txt', 'file1.txt'];

console.log(files.toSorted());
console.log(files.toSorted((a, b) => a.localeCompare(b)));

const natural = new Intl.Collator('en', { numeric: true });
console.log(files.toSorted(natural.compare));

const loose = new Intl.Collator('en', { sensitivity: 'base' });
console.log(loose.compare('a', 'A'), loose.compare('a', 'á'));
Text
[ 'File1.txt', 'file1.txt', 'file10.txt', 'file2.txt' ]
[ 'file1.txt', 'File1.txt', 'file10.txt', 'file2.txt' ]
[ 'file1.txt', 'File1.txt', 'file2.txt', 'file10.txt' ]
0 0

toSorted() with no comparator orders by UTF-16 code units, so every capital letter sorts before every lowercase one: File1.txt comes first. localeCompare fixes the case, and the output puts file1.txt before File1.txt, but file10.txt still lands before file2.txt because the digits are compared one character at a time. With new Intl.Collator('en', { numeric: true }) the digit runs are compared as numbers, and file2.txt comes before file10.txt. Pass natural.compare straight to toSorted(), since it is a bound function. The collation options are in the ECMA-402 specification for Intl.Collator.

The sensitivity: 'base' option ignores case and accents, so a, A and á compare as equal, which is what you want for a search and not for a sorted index. Build the collator once and reuse it for the whole sort. toSorted() needs Node.js 20, or use sort() on a copy.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.