Skip to content

Instantly share code, notes, and snippets.

@tomanistor
Created June 22, 2017 17:41
Show Gist options
  • Save tomanistor/31a60dfe61e8efb2c1559ec79f90af11 to your computer and use it in GitHub Desktop.
Save tomanistor/31a60dfe61e8efb2c1559ec79f90af11 to your computer and use it in GitHub Desktop.
Format a string of names like 'Bart, Lisa & Maggie'.

Given: an array containing hashes of names

Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.

Example:

list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'

list([ {name: 'Bart'}, {name: 'Lisa'} ])
# returns 'Bart & Lisa'

list([ {name: 'Bart'} ])
# returns 'Bart'

list([])
# returns ''

Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'.

function list(names){
return names.map(function(x){ return x.name; }).join(", ").replace(/,(?!.*,)/gmi, " &");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment