stoney_24
stoney_24

Reputation: 125

How to add string to the end of each array element using a for loop?

I am to finish the function below. I am to loop through the arr paramteter using a for loop and add the string "Duck" to the end of each element (i.e. arr[0] = "yellow"; should become "yellowDuck".

Here is what I am given to start with:

function addDucks(arr, ind) {

  //WRITE YOUR FOR-LOOP HERE
  //For your iterator, declare it with the let keyword, and name it "i"


  //DO NOT TOUCH THIS
  return [arr, ind]
} 

Here is the code I am trying:

function addDucks(arr, ind) {
  for (let i = 0; i < arr.length; i++) {
    return arr[i] + 'Duck';
  }
  return [arr, ind]
}

Upvotes: 1

Views: 1618

Answers (1)

pmkro
pmkro

Reputation: 2550

Your code was close, you were just not changing the reference in the array to be the string with Duck added. Modified the return arr[i] + 'Duck' to arr[i] += 'Duck' which is the same as arr[i] = arr[i] + 'Duck'

function addDucks(arr, ind) {
  for (let i = 0; i < arr.length; i++) {
      arr[i] += 'Duck';
  }
  return arr;
}
let ducks = addDucks(['green','purple'], 2);
console.log(ducks);

Upvotes: 1

Related Questions