brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Intl.Collator with numeric: true sorts img2 before img10

Javascript
~/tips/tip-js-intl-collator-natural-sort

const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" });

Natural sort order for file names and versions, ignoring upper and lower case.

A default sort() compares strings character by character, so img10.jpg lands before img2.jpg and every capital letter comes before every lowercase one. Intl.Collator sorts the way people expect.

const files = ["img10.jpg", "img2.jpg", "Img1.jpg", "img20.jpg"];

files.toSorted();
// ["Img1.jpg", "img10.jpg", "img2.jpg", "img20.jpg"]

const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
files.toSorted(collator.compare);
// ["Img1.jpg", "img2.jpg", "img10.jpg", "img20.jpg"]

numeric: true compares runs of digits as numbers, so 2 comes before 10. sensitivity: "base" treats a, A and á as equal when comparing, which is what you want in a list people scan by eye.

The collator’s compare is already bound to it, so I’d pass it straight to sort or toSorted. That matters for speed: a.localeCompare(b, "en", options) gives the same order, but MDN recommends a collator object for large arrays because the options are processed once instead of on every comparison.

The language matters too. Swedish sorts å after z, German does not, so pass the language of the content rather than a fixed one.

It is not a version sorter. 1.10.0 and 1.9.0 come out right, but pre-release tags like 2.0.0-beta follow text rules, not semantic versioning. Use a semver library for those.

Further reading: MDN: Intl.Collator, MDN: Intl.Collator() constructor

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link