Skip to content

Instantly share code, notes, and snippets.

@omeileo
Last active February 9, 2019 21:20
Show Gist options
  • Save omeileo/742c5403fea0895e25c356c1c5524aaf to your computer and use it in GitHub Desktop.
Save omeileo/742c5403fea0895e25c356c1c5524aaf to your computer and use it in GitHub Desktop.
Separate array elements using correct English grammar.
const fruits = ['apple', 'banana', 'orange', 'jackfruit']
let separatedList = ''
fruits.forEach((fruit, index) => {
const isSeparated = fruits.length > 1 && (index + 1 < fruits.length)
const isCommaSeparated = isSeparated && (index + 2 < fruits.length)
const isAmpersandSeparated = isSeparated && (index + 2 === fruits.length)
separatedList = separatedList + fruit
if (isCommaSeparated)
separatedList = separatedList + ', '
if (isAmpersandSeparated)
separatedList = separatedList + ' and '
})
@omeileo
Copy link
Author

omeileo commented Feb 9, 2019

This gist depicts how to create a grammatically correct list* from an array of strings.

*abides by the Oxford comma.

Example:
let fruits = ['apple', 'banana', 'orange', 'jackfruit']
will output apple, banana, orange, and jackfruit

let fruits = ['apple', 'banana']
will output apple and banana

let fruits = ['apple']
will output apple

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment