简体   繁体   中英

Adding two arrays and returning a new array

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;
    }

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])); 

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

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

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM