Last active
February 9, 2019 21:20
-
-
Save omeileo/742c5403fea0895e25c356c1c5524aaf to your computer and use it in GitHub Desktop.
Separate array elements using correct English grammar.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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