1
const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
   const convertToBaby = animals.map((element)=>{
      let newArr = [];
       return newArr.push('baby '+element);
       }

     );
  console.log(convertToBaby);

  Output: [ 1, 1, 1, 1, 1, 1 ]

The expected following output: ['baby panda','baby turtule', and so on...]

2 Answers 2

3

The .push() method returns the length of the array after the new element is added to it. It doesn't return the newly modified array. Since you create a new array each time your callback is executed, the new length after pushing to it will always be 1. Instead, to correctly map your animals, you can return the new element you wish to map the current element to that you're iterated on:

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

As you're only returning within the arrow function's body, you can also simplify it by removing the body and implicitly returning the newly mapped value:

const convertToBaby = animals.map(element => 'baby ' + element);
Sign up to request clarification or add additional context in comments.

2 Comments

Great answer! BTW, you can shorten the map using the implicit return of the arrow function to .map(element => "baby " + element);
@ibrahimmahrir thanks :) I just added a note about that to my answer.
1
const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
const convertToBaby = animals.map((element)=>{
   return 'baby '+element;
   }
 );
console.log(convertToBaby);

This should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.