In my program given an array of hashes of the name. I want to 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.
For e.g.
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 ''
For that, I am mapping values of an array of object using map function and using the slice to extract the last two values of the array and then using toString to convert it into string and then using split("&") to add ampersand between last two elements but I'm not getting output according to expectation.
code:
function list(names){
let result = names.map(value => value.name);
return result.slice(-2).toString().split('&');
}
list([{name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}]);