skip to Main Content

I have to return a new array. Here is the original.

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

I have to return a new array where each string is prepended with ‘baby ‘

I need to use a function but I’m not allowed to use the .map() method.

This is the current code I’m running:

function convertToBaby(arr) {
  for (let i = 0; i < arr.length; i++) {
    return `baby ${arr[i]}`;
  }
}

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

console.log(convertToBaby(animals));

I would imagine it returns the new array, but it only returns baby panda.
What is going on?

2

Answers


  1. The return keyword automatically exits the function, so the for loop only returns the first element.

    If you want to use a loop, you can use:

    function convertToBaby(arr) {
      const newArray = [];
      for (let i = 0; i < arr.length; i++) {
        newArray.push(`baby ${arr[i]}`);
      }
      return newArray;
    }
    
    Login or Signup to reply.
  2. Try using Array.reduce.

    const parents = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
    const babies = parents.reduce( (acc, v) => [...acc, `baby${v}`], []);
    
    console.log(`${parents}n${babies}`);

    Or by looping (notice the return position):

    const parents = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
    const babies = babiesOf(parents);
    
    console.log(`${parents}n${babies}`);
    
    function babiesOf(animals) {
      const babies = [];
      
      for (let i = 0; i < animals.length; i += 1) {
        babies[i] = `baby${animals[i]}`;
      }
      // return should be out of the loop
      return babies;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search