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
The
return
keyword automatically exits the function, so thefor
loop only returns the first element.If you want to use a loop, you can use:
Try using
Array.reduce
.Or by looping (notice the
return
position):