Javascript - Sum two arrays in single iteration

后端 未结 13 1998
我寻月下人不归
我寻月下人不归 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:09

    All the above mentioned answer is correct,

    Using reduce. I just want to add my answer might be simple and useful.

    var array1 = [1,2,3,4];
    var array2 = [5,6,7,8];
    
    const reducer = (accumulator, currentValue, index, array) => {
        let val = currentValue + array2[index];
        accumulator.push(val);
        return accumulator;
    }
    
    
    console.log(array1.reduce(reducer, []));

    Thanks..

    0 讨论(0)
  • 2020-11-29 06:11

    This example will work with different length variation:

    let getSum = (arr1, arr2) =>  {
       let main = arr1.length >= arr2.length ? arr1 : arr2;
       let sec = arr1.length < arr2.length ? arr1 : arr2;
       return main.map((elem, i) => sec[i] ? elem + sec[i] : elem)
    }
    
    0 讨论(0)
  • 2020-11-29 06:12

    You can do it using some functional style:

    const a = [1,2,3]
    const b = [4,5,6]
    
    const f= a.concat(b).map((v,i,arr)=>{
      if ( i<arr.length) return v+arr[i+arr.length/2]
    }).filter(n=>!isNaN(n))
    
    console.log(f)
    
    0 讨论(0)
  • 2020-11-29 06:13

    You can use the _.unzipWith method from the Lodash library.

    var array1 = [1, 2, 3, 4];
    var array2 = [5, 6, 7, 8];
    var array = [array1, array2];
    console.log(_.unzipWith(array, _.add));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    0 讨论(0)
  • 2020-11-29 06:14
    var arr = [1,2,3,4];
    var arr2 = [1,1,1,2];
    
    var squares = arr.map((a, i) => a + arr2[i]);
    
    console.log(squares);
    
    0 讨论(0)
  • 2020-11-29 06:15

    Another way to do it could be like that

    var array1 = [1,2,3,4];
    var array2 = [5,6,7,8];
    
    var sum = [...array1].map((e,i)=> e+array2[i]); //[6,8,10,12]
    

    In this case [...array1] is the same to [1,2,3,4]

    0 讨论(0)
提交回复
热议问题