array sum of two arrays code example
Example 1: sum of two array in javascript
function sumArrays(...arrays) {
const n = arrays.reduce((max, xs) => Math.max(max, xs.length), 0);
const result = Array.from({ length: n });
return result.map((_, i) => arrays.map(xs => xs[i] || 0).reduce((sum, x) => sum + x, 0));
}
console.log(...sumArrays([0, 1, 2], [1, 2, 3, 4], [1, 2]));
Example 2: addition of two arrays
int[] a = {10, 20 30, 40}; int[] b = {25, 50, 75, 100, 125}; int[] sum = new int[b.length]; for (int i = 0; i <= b.length; i++){ sum[i] = 0; if (i > b.length){ sum[i] = b[i] + 0; else{ sum[i] = a[i] + b[i]; } }
Example 3: sum of two array in javascript
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;
}