This site runs best with JavaScript enabled.

Listify a JavaScript Array

Photo by Kelly Sikkema


Make a human readable list from an array in JavaScript.

When you want to display a list of items to a user, I'm afraid .join(', ') just won't cut it:

1console.log(['apple'].join(', ')) // apple
2// looks good
3console.log(['apple', 'grape'].join(', ')) // apple, grape
4// nah, I want "apple and grape"
5console.log(['apple', 'grape', 'pear'].join(', ')) // apple, grape, pear
6// wut?

Ok, so bust out your string concat skills right? That's what I did... but holdup, there's a better way:

Have you heard of Intl.ListFormat? Well, it's likely that this can do all you need and more. Let's take a look:

1const items = [
2 'Sojourner',
3 'Opportunity',
4 'Spirit',
5 'Curiosity',
6 'Perseverance',
7]
8
9const formatter = new Intl.ListFormat('en', {
10 style: 'long',
11 type: 'conjunction',
12})
13console.log(formatter.format(items))
14// logs: "Sojourner, Opportunity, Spirit, Curiosity, and Perseverance"

The cool thing about this is that because it's coming from the Intl standard, a TON of locales are supported, so you can get internationalization for "free".

The first argument to the ListFormat constructor is the locale (we're using 'en' above for "English"). The second argument is the options of style and type. The style option can be one of 'long', 'short', or 'narrow'. The type can be one of 'conjunction', 'disjunction', or 'unit'.

With the list above, here's all the combination of those (with en as the locale):

long
conjunctionSojourner, Opportunity, Spirit, Curiosity, and Perseverance
disjunctionSojourner, Opportunity, Spirit, Curiosity, or Perseverance
unitSojourner, Opportunity, Spirit, Curiosity, Perseverance
short
conjunctionSojourner, Opportunity, Spirit, Curiosity, & Perseverance
disjunctionSojourner, Opportunity, Spirit, Curiosity, or Perseverance
unitSojourner, Opportunity, Spirit, Curiosity, Perseverance
narrow
conjunctionSojourner, Opportunity, Spirit, Curiosity, Perseverance
disjunctionSojourner, Opportunity, Spirit, Curiosity, or Perseverance
unitSojourner Opportunity Spirit Curiosity Perseverance

Interestingly, if we play around with the locale, things behave unexpectedly:

1new Intl.ListFormat('en', {style: 'narrow', type: 'unit'}).format(items)
2// Sojourner Opportunity Spirit Curiosity Perseverance
3
4new Intl.ListFormat('es', {style: 'narrow', type: 'unit'}).format(items)
5// Sojourner Opportunity Spirit Curiosity Perseverance
6
7new Intl.ListFormat('de', {style: 'narrow', type: 'unit'}).format(items)
8// Sojourner, Opportunity, Spirit, Curiosity und Perseverance

Perhaps German speakers can clear up for us why the combo of narrow and unit for de behaves more like long and conjunction because I have no idea.

There's also a lesser-known localeMatcher option which can be configured to either 'lookup' or 'best fit' (defaults to 'best fit'). As far as I can tell from mdn, its purpose is to tell the browser how to determine which locale to use based on the one given in the constructor. In my own testing I was unable to determine a difference in functionality switching between these options 🤷‍♂️

Frankly, I think it's typically better to trust the browser on stuff like this rather than write what the browser offers. This is because the longer I spend time writing software, the more I find that things are rarely as simple as we think they'll be (especially when it comes to internationalization). But there are definitely times where the platform comes up short and you can't quite do what you're looking to do. That's when it makes sense to do it yourself.

So I put together a little function that suited my use case pretty well, and I want to share it with you. Before I do, I want to be clear that I did try this without reduce (using a for loop) and I think the reduce method was considerably simpler. Feel free to take a whack at the for loop version though if you want.

1function listify(
2 array,
3 {conjunction = 'and ', stringify = item => item.toString()} = {},
4) {
5 return array.reduce((list, item, index) => {
6 if (index === 0) return stringify(item)
7 if (index === array.length - 1) {
8 if (index === 1) return `${list} ${conjunction}${stringify(item)}`
9 else return `${list}, ${conjunction}${stringify(item)}`
10 }
11 return `${list}, ${stringify(item)}`
12 }, '')
13}

In my codebase, is used like so:

1const to = `To: ${listify(mentionedMembersNicknames)}`
2// and
3const didYouMean = `Did you mean ${listify(closeMatches, {
4 conjunction: 'or ',
5})}?`

I'd take the time to walk through this code with you, but actually as I was writing this post, I realized that my use case wasn't as special as I thought it was and I tried rewriting this to use Intl.ListFormat and wouldn't you know it, with a small change to the API, I was able to make a simpler implementation on top of the standard:

1function listify(
2 array,
3 {
4 type = 'conjunction',
5 style = 'long',
6 stringify = item => item.toString(),
7 } = {},
8) {
9 const stringified = array.map(item => stringify(item))
10 const formatter = new Intl.ListFormat('en', {style, type})
11 return formatter.format(stringified)
12}

With that, now I do this:

1// no change for the default case
2const to = `To: ${listify(mentionedMembersNicknames)}`
3// switch to using the "type" option rather than overloading/abusing the term "conjunction"
4const didYouMean = `Did you mean ${listify(closeMatches, {
5 type: 'disjunction',
6})}?`

Conclusion

So it just goes to show you that you might be doing some extra work that you might not need to be doing. The platform probably does this for you automatically! Oh, and just for fun, here's a TypeScript version of that finished code (I'm in the process of migrating this project to TypeScript).

1// unfortunately TypeScript doesn't have Intl.ListFormat yet 😢
2// so we'll just add it ourselves:
3type ListFormatOptions = {
4 type?: 'conjunction' | 'disjunction' | 'unit'
5 style?: 'long' | 'short' | 'narrow'
6 localeMatcher?: 'lookup' | 'best fit'
7}
8declare namespace Intl {
9 class ListFormat {
10 constructor(locale: string, options: ListFormatOptions)
11 public format: (items: Array<string>) => string
12 }
13}
14
15type ListifyOptions<ItemType> = {
16 type?: ListFormatOptions['type']
17 style?: ListFormatOptions['style']
18 stringify?: (item: ItemType) => string
19}
20function listify<ItemType>(
21 array: Array<ItemType>,
22 {
23 type = 'conjunction',
24 style = 'long',
25 stringify = (thing: {toString(): string}) => thing.toString(),
26 }: ListifyOptions<ItemType> = {},
27) {
28 const stringified = array.map(item => stringify(item))
29 const formatter = new Intl.ListFormat('en', {style, type})
30 return formatter.format(stringified)
31}

And now we get sweet autocomplete for those options and type checking on that stringify method. Nice!

Oh, by the way, you'll always want to double-check browser support for whatever you're using. There's caniuse.com and the MDN article on Intl.ListFormat also has a chart.

I hope that was interesting and useful to you!

Discuss on TwitterEdit post on GitHub

Share article
Kent C. Dodds

Kent C. Dodds is a JavaScript software engineer and teacher. He's taught hundreds of thousands of people how to make the world a better place with quality software development tools and practices. He lives with his wife and four kids in Utah.

Join the Newsletter



Kent C. Dodds