Tom Spatula
Tom Spatula

Reputation: 49

Why does my map function return an array of ones instead of an array strings?

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...]

Upvotes: 1

Views: 49

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50674

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);

Upvotes: 3

Daniel Lee
Daniel Lee

Reputation: 11

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

This should work.

Upvotes: 1

Related Questions