How would I loop through an array in Javascript, add a word, then return an array (without using map)?

Viewed 413

How would I loop through an array in Javascript, add a word, and then return an array (without using map)?

var convertToBaby = (array) => {
  for (var i =0; i < array.length; i++) {
    console.log('baby '+ array[i]);
  }
};

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

/*Returns 

baby panda
baby turtle
baby giraffe
baby hippo
baby sloth
baby human */

// Should return ['baby panda', 'baby turtle', 'baby giraffe', 'baby hippo', 'baby sloth', 'baby human'];
5 Answers

maybe this

var convertToBaby = (array) => {
    let arr = [];
    for (var i =0; i < array.length; i++) {
    arr.push('baby '+ array[i])
    }
    console.log(arr);
    return arr;
  
};

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

You can (ab)use reduce to return a new array matching the criterion you specified:

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

const newArr = array.reduce((newArr, anim) => !newArr.push('baby ' + anim) || newArr, []);

console.log(newArr);// ['baby panda', 'baby turtle', 'baby giraffe', 'baby hippo', 'baby sloth', 'baby human']

You can push the modified elements to a new array using forEach.

var convertToBaby = (array) => {
  const res = [];
  array.forEach(x => res.push('baby ' + x));
  return res;
};
const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
console.log(convertToBaby(animals));

You could use forEach or reduce to pass the new values to a new array without mutating the original array

const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
var newarray=[]
animals.forEach(element=>newarray.push("baby "+element))
console.log(newarray)

However if the reason why you don't want to use map it's because you don't want to make a new array and want to mutate the initial array you could splice each element and replace it with the new element but I don't recommend it

 const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human'];
 for(let i=0;i<animals.length;i++){
        el="baby "+animals[i] 
        animals.splice(i,1)
        animals.unshift(el)
 }
console.log(animals.reverse())

const convertToBaby = arr => {
      const babyArray = [];
      for (let i = 0; i < arr.length; i++) {
            babyArray.push('baby ' + arr[i]);
      }
      return babyArray;
};

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


convertToBaby(animals);
Related