can i sum the elements of arbitrary number of arrays with different lengths in javascript?

Use a nested array, and loop over the array rather than hard-coding two array variables.

You can use to get all the lengths so you can calculate the maximum length. And arrays.reduce() to sum up an element in each array.

const addTogether = (...arrays) => {
  let result = [];
  let len = Math.max( => a.length));
  for (let i = 0; i < len; i++) {
    result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0));
  return result

console.log(addTogether([1, 2, 3], [4, 5], [6]));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top