Intl.ListFormat
Andrew Lai
May 22nd, 2022
Chances are, if you've worked with currency or date/time in javascript, you've used Intl. But did you know about the ListFormat option? I was trying to format an array of names into a proper english list like "Apple, Banana, and Cake" but the number of names could range from 1 to 3 or more. My first gut reaction was make my own function that checks all the conditions. Something like:
if (!list?.length) {
return "";
}
if (list.length === 1) {
return list[0];
}
if (list.length === 2) {
return list.join(' and ');
}
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
With Intl.ListFormat though, it takes care of all that for me and even formats in other locales (though I'm only doing English for this site). I can just call a simple format function and I don't need to worry about the commas or the number of elements in the array:
const authors = [{ id: 'a', name: 'Apple'}, { id: 'b', name: 'Banana'}, { id: 'c', name: 'Cake'}];
const names = authors.map((author) => author.name);
const lf = new Intl.ListFormat('en');
lf.format(names)
// Apple, Banana, and Cake
I did get a typescript error in my IDE though and found that the type definitions were just added. Unfortunately, it looks like it hadn't made it into the latest stable release yet so I had to add my declare my own Intl namespace with the ListFormat interfaces.