JavaScriptFundamental (ES6), part 1
Sort names with Intl.Collator in JavaScript
136 sort names properly, with a fixed locale
fairSort a list of Nigerian names and show that the default sort() gets it wrong: it compares UTF-16 code units, so every capital comes before every lowercase and the Yoruba letters land past z. Fix it with localeCompare and an explicit locale, then with a reused Intl.Collator. Use sensitivity to make a search ignore case and accents, and numeric to order stall numbers.
Stuck? Three hints, smallest first
- 1. A comparator returns a negative number, zero or a positive number —
a.localeCompare(b, locale)already is one. - 2. Always pass the locale. Left out, it uses whatever the machine is set to, so the same code sorts differently on two computers.
- 3.
{ sensitivity: 'base' }treatse,éandEas equal;{ numeric: true }compares runs of digits as numbers.
const names = ['Ọladele', 'Adéwálé', 'adebayo', 'Zainab', 'Chinedu', 'Ẹmeka', 'Ibrahim'];
const byCodeUnit = [...names].sort();
const byLocale = [...names].sort((a, b) => a.localeCompare(b, 'en-NG'));
const collator = new Intl.Collator('en-NG');
const byCollator = [...names].sort(collator.compare);
const loose = new Intl.Collator('en-NG', { sensitivity: 'base' });
const accentPair = [loose.compare('Adéwálé', 'Adewale'), collator.compare('Adéwálé', 'Adewale')];
const casePair = [loose.compare('adebayo', 'Adebayo'), Math.abs(Math.sign(collator.compare('adebayo', 'Adebayo')))];
const stalls = ['Stall 10', 'Stall 2', 'Stall 1'];
const byText = [...stalls].sort((a, b) => a.localeCompare(b, 'en-NG'));
const byNumber = [...stalls].sort((a, b) => a.localeCompare(b, 'en-NG', { numeric: true }));
const signs = ['adebayo'.localeCompare('Zainab', 'en-NG'), 'Zainab'.localeCompare('adebayo', 'en-NG')].map(Math.sign);
const found = names.filter((n) => loose.compare(n, 'adewale') === 0);
console.log('code units:', byCodeUnit);
console.log('locale :', byLocale);
console.log('stalls :', byText, '->', byNumber);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the default sort strands lowercase and the Yoruba letters after Z', byCodeUnit, ['Adéwálé', 'Chinedu', 'Ibrahim', 'Zainab', 'adebayo', 'Ẹmeka', 'Ọladele']);
test('localeCompare with an explicit locale puts them where a reader expects', byLocale, ['adebayo', 'Adéwálé', 'Chinedu', 'Ẹmeka', 'Ibrahim', 'Ọladele', 'Zainab']);
test('a reused Collator gives the same order, and is the faster way to sort', byCollator, byLocale);
test('at base sensitivity the accents stop mattering; by default they do', [accentPair[0], Math.abs(Math.sign(accentPair[1]))], [0, 1]);
test('and so does case, which is what you want for a search box', casePair, [0, 1]);
test('so a loose comparison finds a name typed without its diacritics', found, ['Adéwálé']);
test('as text, Stall 10 sorts before Stall 2', byText, ['Stall 1', 'Stall 10', 'Stall 2']);
test('numeric: true reads the digits as a number and fixes it', byNumber, ['Stall 1', 'Stall 2', 'Stall 10']);
test('only the sign of the result is specified, never the magnitude', signs, [-1, 1]);
Array.prototype.sort with no comparator converts to strings and compares UTF-16 code units. That is why every capital letter sorts before every lowercase one — 'Z' is 90, 'a' is 97 — and why Ẹ and Ọ, which live in the Latin Extended Additional block, end up past z entirely. For any list a person will read, it is simply the wrong comparison.
Passing the locale explicitly is the habit to build. localeCompare(b) with no locale uses the host's setting, so the same code produces different orders on your laptop and the server, and a test that passes locally fails in CI. And when you are sorting more than a handful of items, build one Intl.Collator and pass collator.compare — localeCompare constructs a collator per comparison unless the engine caches it.
sensitivity: 'base' is the setting worth remembering. It makes Adéwálé, Adewale and ADEWALE compare equal, which is what a search box needs: someone typing without diacritics still finds the record. The last assertion is the API's own small print — the result is a sign, not a distance, so compare it against zero and never against -1 or 1.