Search code examples
javascriptarraysstringfunctionformatting

How to join array elements into string with commas & ampersand?


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'}]);

Solution

  • It's a bit tricker than that, since you'll have to separate out the final name in the list from the rest initially, then join the rest. If there are any in the rest, then concatenate the joined string with ' and ', else return the final name only:

    function list(people){
      const names = people.map(({ name }) => name);
      const finalName = names.pop();
      return names.length
      ? names.join(', ') + ' & ' + finalName
      : finalName;
    }
    
    console.log(list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])) // returns 'Bart, Lisa & Maggie'
    console.log(list([ {name: 'Bart'}, {name: 'Lisa'} ])) // returns 'Bart & Lisa'
    console.log(list([ {name: 'Bart'} ])) // returns 'Bart'

    Note that the input is not an array of names - it's an array of objects that need to be mapped to names later, so you might name your variables more precisely and give list an argument of people (or something like that) rather than names.