Format JavaScript Array of Strings to Oxford Comma
const toOxfordComma = (array) =>
array.length === 2
? array.join(' and ')
: array.length > 2
? array
.slice(0, array.length - 1)
.concat(`and ${array.slice(-1)}`)
.join(', ')
: array.join(', ')
toOxfordComma(['Apples'])
// Apples
toOxfordComma(['Apples', 'Bananas'])
// Apples and Bananas
toOxfordComma(['Apples', 'Bananas', 'Pears'])
// Apples, Bananas, and Pears
toOxfordComma(['Apples', 'Bananas', 'Pears', 'Oranges'])
// Apples, Bananas, Pears, and Oranges
Nice, Browser support looks pretty good now too vs 2019 when I wrote this – thanks for the tip.