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
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..
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)
}
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)
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>
var arr = [1,2,3,4];
var arr2 = [1,1,1,2];
var squares = arr.map((a, i) => a + arr2[i]);
console.log(squares);
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]