Map in forEach method the first key and value is not working

Hi Rasul,

That one caught me out for while :slight_smile:

You are using the same key name ‘Shakira’ twice.

const playlist = new Map([
  ["Shakira", "Loca Loca"], // key is "Shakira"
  ["Ricky Martin", "I don't care"],
  ["Shakira", "Whenever, whenever"], // key is "Shakira"
])

or

const playlist = new Map()

playlist.set('Shakira', 'Loca Loca') // <- Shakira is set
playlist.set('Ricky Martin', "I don't care") // <- Ricky Martin is set
playlist.set('Shakira', 'Whenever, whenever') // <- Shakira is overwritten

playlist.forEach((song, artist) => console.log(`${artist} - ${song}\n`));

// Shakira - Whenever, whenever <- over written value
// Ricky Martin - I don't care

Maybe use an array and destructuring?

const playlist = [
  ['Shakira', 'Loca Loca'], 
  ['Ricky Martin', "I don't care"], 
  ['Shakira', 'Whenever, whenever']
]
  
playlist.forEach(([artist, song]) => console.log(`${artist} - ${song}\n`));

// Shakira - Loca Loca
// Ricky Martin - I don't care
// Shakira - Whenever, whenever

For example

1 Like

Thanks, I did not know about set. I guessed that problem was keys are the same. Thanks. I did not know that It was set.

1 Like