Skip to content
jshacks.dev
Fundamentals

Pick plural forms with Intl.PluralRules

Pick singular and plural forms with Intl.PluralRules, and build ordinals like 1st, 2nd and 3rd from the ordinal type. Node.js 18 and later.

2 min read
Summarize in AI

n === 1 ? 'file' : 'files' works in English and fails in Russian, Arabic and every language with more than two forms. Intl.PluralRules returns the category the language actually uses, on Node.js 18 and later.

JavaScript
const cardinal = new Intl.PluralRules('en-US');
const ordinal = new Intl.PluralRules('en-US', { type: 'ordinal' });

const files = (n) => `${n} file${cardinal.select(n) === 'one' ? '' : 's'}`;
console.log(files(1), files(0), files(2));

const suffix = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
console.log([1, 2, 3, 4, 11, 12, 13, 21, 22, 101].map((n) => n + suffix[ordinal.select(n)]));
console.log(new Intl.PluralRules('ar').select(2), new Intl.PluralRules('ru').select(3));
Text
1 file 0 files 2 files
[
  '1st',  '2nd',
  '3rd',  '4th',
  '11th', '12th',
  '13th', '21st',
  '22nd', '101st'
]
two few

select(n) returns a string such as one or other and you map it to your own words. In English the cardinal categories are one and other, so 0 files and 2 files share a form. The ordinal type gives one, two, few and other, which the example maps to st, nd, rd and th, and handles 11th, 12th and 13th correctly, where a naive last-digit rule fails. Russian and Arabic return more categories, as the last line shows for 3 in Russian (few) and 2 in Arabic (two). The categories are defined by CLDR and exposed by ECMA-402 Intl.PluralRules.

The method returns only a category. You still need a translated string for each one, and Intl.NumberFormat for the number.

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.