0

Goal --> I am trying to complete a codesmith challenge: For Loops - Updating Array Elements

Using a FOR loop, write a function addN which adds the argument n to each number in the array arr and returns the updated arr.

Problem --> the for loop only console logs a single value (4 and 5 for each log) and does not update each value in the array.

My input --> I have googled and watched youtube videos on for loops and forEach, but I am still at a wall. I believe something is wrong in my return as it returns only a single value and not an updated array. Please can you point me in the right direction...

my code -->

function addN(arr, n){
  // ADD CODE HERE
  for (let i = 0; i < arr.length; i++) {
   
    return arr[i] += n;
     // return number;
  }
 
} 

// Uncomment these to check your work!
console.log(addN([1, 2, 3], 3)); // expected log [4, 5, 6]
console.log(addN([3, 4, 5], 2)); // expected log [5, 6, 7]

2 Answers2

1

You must return all array instead of single for loop like:

function addN(arr, n){
  // ADD CODE HERE
  for (let i = 0; i < arr.length; i++) {
     arr[i] += n;
  }
  return arr;
 
} 

// Uncomment these to check your work!
console.log(addN([1, 2, 3], 3)); // expected log [4, 5, 6]
console.log(addN([3, 4, 5], 2)); // expected log [5, 6, 7]
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

The return must be placed after the loop:

function addN(arr, n){
  for (let i = 0; i < arr.length; i++) {
    arr[i] += n;
  }
  return arr;
} 

// Uncomment these to check your work!
console.log(addN([1, 2, 3], 3)); // expected log [4, 5, 6]
console.log(addN([3, 4, 5], 2)); // expected log [5, 6, 7]

Also, you can check the high order function Array.prototype.map()

function addN(arr, n){
  return arr.map(x => x + n);
} 

// Uncomment these to check your work!
console.log(addN([1, 2, 3], 3)); // expected log [4, 5, 6]
console.log(addN([3, 4, 5], 2)); // expected log [5, 6, 7]
Greedo
  • 3,438
  • 1
  • 13
  • 28