javascript to find sum of 2 numbers in array code example

Example 1: sum of all numbers in an array javascript

const arrSum = arr => arr.reduce((a,b) => a + b, 0)

Example 2: 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])); // 2 5 5 4