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 :(
CodePudding user response:
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);
CodePudding user response:
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 }
];
// use `split` to split
console.log(players.map(player => player.name.split(', ')))
CodePudding user response:
If you really have to use split, which then you would have to use join to change it back to a string:
{ 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 }
];
const mapped = players.map(({ name }) => {
let splitName = name.split(',');
return splitName.join('')
})
console.log(mapped);
But I think this would be better:
{ 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 }
];
const mapped = players.map(({ name }) => {
return name.replace(',', '')
})
console.log(mapped);