Search code examples
javascriptarrayssplit

How can I remove comma between first and last names in array?


I have to remove the comma between the first and last names of "name" in an array called "players" using .map() and .split().

This is the array I'm given:

const players = [
  { name: 'Modrić, Luka', year: 1985 },
  { name: 'Christian, Eriksen', year: 1992 },
  { name: 'Griezmann, Antoine', year: 1991 },
  { name: 'Achraf, Hakimi', year: 1998 },
  { name: 'Martínez, Lautaro', year: 1997 }
];

This is the code I have so far, to get name out of the array using .map():

const mapped = players.map(({ name }) => {
  return name;
})
console.log(mapped);

Which logs this in the console:

[
  'Modrić, Luka',
  'Christian, Eriksen',
  'Griezmann, Antoine',
  'Achraf, Hakimi',
  'Martínez, Lautaro'
]

Now how do I use .split() to remove the the commas between the first and last name? Im lost :(

Thanks for any help! :)

I tried using .map to get each name from the players array. Then I tried using .split() to no avail :(


Solution

  • You can use String#replace.

    const players = [
      { name: 'Modrić, Luka', year: 1985 },
      { name: 'Christian, Eriksen', year: 1992 },
      { name: 'Griezmann, Antoine', year: 1991 },
      { name: 'Achraf, Hakimi', year: 1998 },
      { name: 'Martínez, Lautaro', year: 1997 }
    ];
    let res = players.map(({name}) => name.replace(',', ''));
    console.log(res);