Human readable lists from arrays
Last updated
Here’s an easy way to format an array as a human readable list in JavaScript:
const authors = ["Ronald L. Rivest", "Adi Shamir", "Len Adleman"];
const formatter = new Intl.ListFormat("en", {
style: "long",
type: "conjuction",
});
console.log(formatter.format(authors));
// expected output:
// Ronald L. Rivest, Adi Shamir, and Len Adleman
The Intl.ListFormat
object enables language-sensitive list formatting. If you pass a different language code, say pt-br
for Brazilian Portuguese, you’d get:
// Ronald L. Rivest, Adi Shamir e Len Adleman
The Oxford comma
This is where things get weird. In Portuguese the output has no Oxford comma. Some English locales return it, some don’t; eu-AU
and en-GB
for instance do not include it, but for en
and en-US
it is there.
I did a bit of research to find out why some locales include it and some not, but couldn’t find the reason why this is.
Browser support
Pretty much every modern browser supports this out-of-the-box, with the only expection being Safari and IE. If you need to support those lessers browsers there’s a polyfill available on GitHub.