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){
if (names.length > 3) {
let array = []
for (let i = 0; i < names.length; i++) {
if (i === 0 || i === names.length) {
array.push(`${names[i].name},`);
}else if (i !== names.length -1 && i !== names.length -2) {
array.push(` ${names[i].name},`);
}else if (i !== names.length -1) {
array.push(` ${names[i].name} & `);
} else {
array.push(`${names[names.length -1].name}`)
}
}
return array.join('');
}
if (names.length === 3) {
return `${names[0].name}, ${names[1].name} &
${names[2].name}`
} else if (names.length === 2) {
return `${names[0].name} & ${names[1].name}`
} else if (names.length === 1) {
return names[0].name
} else {
return ""
}
}