Javascript - Sum two arrays in single iteration

后端 未结 13 2076
我寻月下人不归
我寻月下人不归 2020-11-29 05:56

I want to sum each value of an array of numbers with its corresponding value in a different array of numbers, and I want to do this without looping through each individual v

13条回答
  •  隐瞒了意图╮
    2020-11-29 06:25

    Below example will work even with length variation and few more use cases. check out. you can do prototyping as well if you needed.

    function sumArray(a, b) {
          var c = [];
          for (var i = 0; i < Math.max(a.length, b.length); i++) {
            c.push((a[i] || 0) + (b[i] || 0));
          }
          return c;
    }
    
    // First Use Case.
    var a = [1, 2, 3, 4];
    var b = [1, 2, 3, 4];
    console.log( sumArray(a, b) );
    
    // Second Use Case with different Length.
    var a = [1, 2, 3, 4];
    var b = [1, 2, 3, 4, 5];
    console.log( sumArray(a, b) );
    
    // Third Use Case with undefined values and invalid length.
    var a = [1, 2, 3, 4];
    var b = [];
    b[1] = 2;
    b[3] = 4;
    b[9] = 9;
    console.log( sumArray(a, b) );

提交回复
热议问题