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
thanks for sharing this! thought i'd let you know it fails with a list of 2.
['apple', 'orange']
comes out asapple, orange
but should beapple and orange
.