2

Write a function addArrays that takes 2 arrays of numbers as parameters and returns a new array where elements at same index position are added together. For example: addArrays([1,2,3], [4,3,2,1]); // => [5,5,5,1]

I am trying to use nested for loops but its giving an incorrect answers....

  function addArrays(num1, num2){
      var result = [];
      for(var i=0; i< num1.length; i++){
        for(var j=0; j<num2.length; j++){
          result.push(num1[i] + num2[j]);
      }
      }
      return result;
    }
3
  • possible duplicate of stackoverflow.com/questions/24094466/… Commented May 19, 2016 at 18:57
  • 1
    Sounds like a school assignment. Tsk tsk. Commented May 19, 2016 at 18:58
  • No need for nested loops, but you have to check arrays length... Commented May 19, 2016 at 19:00

4 Answers 4

4

I suggest to use only one loop with a check of the length and some default values if the elements do not exists.

function addArrays(array1, array2) {
    var i,
        l = Math.max(array1.length, array2.length),
        result = [];
    for (i = 0 ; i < l; i++) {
        result.push((array1[i] || 0) + (array2[i] || 0));
    }
    return result;
}

console.log(addArrays([1, 2, 3], [4, 3, 2, 1]));

Sign up to request clarification or add additional context in comments.

Comments

2

There is no need to nest with 2 loops. Nested loops for arrays are used if you have a 2 dimensional array.

function addArrays(num1, num2){
    var result = [];
    var size = Math.max(num1.length, num2.length);

    for(var i = 0; i < size; i++){
        result.push(num1[i] + (num2[i]);

    }
    return result;
}

You can also default it to 0 if the arrays are different lengths and you go off the end like this

(num1[i] || 0) + (num2[i] || 0)

This chooses either the number in the array, or 0 if it doesnt exist

Comments

0
function addArrays(num1, num2){
      var result = [];
      for(var i=0; i< num1.length; i++){
          result.push(num1[i] + num2[i]);
      }
      return result;
}

Comments

0

For those a little more progressive in nature...

let a = [1, 2, 3], b = [4, 3, 2, 1], l = Math.max(a.length, b.length)
const addArrays = ((a[l-1]) ? a : b).map((v, k) => (a[k] || 0) + (b[k] || 0))

console.log(addArrays) // [ 5, 5, 5, 1 ]

1 Comment

Math.max(...a, ...b) it does not check the length, but the elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.