When you have a list of name or items in an array, you can quickly convert the array into a string so they read in natural language (*, *, and *) with the Intl.ListFormat object.
That means you can convert [‘jim’, ‘joe’, ‘pearl’, ‘pam’] into “jim, joe, pearl, and pam” with the following code:
new Intl.ListFormat('en-US').format(['jim', 'joe', 'pearl', 'pam'])
// output: 'jim, joe, pearl, and pam'
The format method lives on the ListFormat object and can be invoked immediately or later, as shown below.
That replaces this mess…
ARRAY.slices(0, -1).join(',').contact(', and ', ARRAY.slice(-1))
Syntax
new Intl.ListFormat(locales, options)
All arguments are optional.
Note: See the Intl.ListFormat MDN docs for more information.
Customize the output
You can change up the output with several optional arguments.
1. locales
Javascript uses locale codes to determine how to format the string based on the locales argument.
If you’re an English speaker, your most likely reason for changing from your default local parameter is if you have a preference about the Oxford Comma. (It’s the comma that separates the last two items in a list.)
en-US
: jim, joe, pearl, and pam (Oxford comma)en-GB
: jim, joe, pearl and pam (no Oxford comma)
2. options
You can pass an object as a second argument with as many as three different options:
- localMatcher: choose which locale matching algorithm to use (‘best fit’ is the default)
- type: ‘conjunction’ (default), ‘disjunction’, or ‘unit’
- style: ‘long’ (default), ‘short’ (works only with unit type), or ‘narrow’(works only with unit type)
Note: The options are passed in as strings … so { type: 'conjunction'}.
I’ll let you read the MDN docs for a full explanation, but I think I’ll mostly reach for the type option.
- type: conjunction (returns “and” — the default)
- type: disjunction (returns “or” — the default)
new Intl.ListFormat('en-US', {type: 'conjunction'}).format(['jim', 'joe', 'pearl', 'pam'])
// output: 'jim, joe, pearl, and pam'
new Intl.ListFormat('en-US', {type: 'disjunction'}).format(['jim', 'joe', 'pearl', 'pam'])
// output: 'jim, joe, pearl, and pam'
Best practices
It seems like the best approach is to create a new formatter object and then reference that object when you need an array formatted.
const formatOR = new Intl.ListFormat('en-US', {type: 'disjunction'});
You’d then call the format
method on that object with any array(s) you want formatted.
formatOR.format(['jim', 'joe', 'pearl', 'pam']);
// output: 'jim, joe, pearl, and pam'