Skip to content

Instantly share code, notes, and snippets.

@adamburmister
Created September 15, 2017 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamburmister/94ce23639929e13f4a492414c83e025c to your computer and use it in GitHub Desktop.
Save adamburmister/94ce23639929e13f4a492414c83e025c to your computer and use it in GitHub Desktop.
Convert names array to sentence structure
function cleanNameInput(names) {
return names
.map(name => name.trim())
.filter(name => name)
}
function namesToSentence(names = [], options = {}) {
names = cleanNameInput(names)
const before = names.slice(0, options.length || -1)
const after = names.slice(options.length || -1)
return `${before.join(', ')} and ${(after.length > 1) ? `${after.length} others` : after.join()}`
}
// namesToSentence(['susy', 'john', 'mary', 'sally', 'adam', 'jessa'])
// => "susy, john, mary, sally, adam and jessa"
// namesToSentence(['susy', 'john', 'mary', , , 'jessa'])
// => "susy, john, mary and jessa"
// namesToSentence(['susy', 'john', 'mary', 'sally', 'adam', 'jessa'], { length: 3 })
// => "susy, john, mary and 3 others"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment