javascriptarraysarray.prototype.map

how can I use the .map() method and print baby in front of each element in the array?


const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];

const babyAnimals = animals.map((baby) => {
  return `baby ${animals}`;
})
console.log(babyAnimals);

I want the code to print

['baby panda', 'baby turtle', 'baby giraffe', 'baby hippo', 'baby sloth', 'baby human']

I used the for loop method and it worked but I'm trying to use .map method and I haven't been able to figure it out


Solution

  • In your map function, you are returning the entire animals array instead of the current element baby. You should update your map function to use the current element:

    const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
    
    const babyAnimals = animals.map((baby) => {
        return `baby ${baby}`;
    })  
    console.log(babyAnimals);