Solution to Day 6 of 7 Days of JS

4 December 2019

I first wrote this code using the push() method:

function sumToArray(n, array){
  let length = array.length;
  let output = []
  for (let i = 0; i < length; i++){
    output.push(array[i]+n);
  }
  return output;
}

console.log(sumToArray(5,[1,2,3,4]))

Then, using concatenation:

function sumToArray1(n, array){
  let length = array.length;
  let output = []
  for (let i = 0; i < length; i++){
    output += (n + array[i] + '.');
  }
  return output;
}

console.log(sumToArray1(5,[2,3,5]))

This returns a string, not an array.

And finally, using the map() method:

function sumToArray2(n, array){
  return array.map(function (element){
    return element + 2;
  })
}

console.log(sumToArray2(1,[7,13,2]))

Any question? Write a comment!

See ya!