Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Sum Of Two Arrays where arrays can be of unequal length

Tags:

javascript

I need function like this.

function sum(arr1, arr2) {
  return totalArray
};

sum([1,2,3,4], [5,6,7,8,9]) // [6,8,10,12,9]

I tried it this way:

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

1 Answers

First you can get an array out of the function's arguments using Spread syntax (...), then sort it by array's length using Array.prototype.sort() and finally Array.prototype.reduce() to get the result array

Code:

const sum =(...arrays) => arrays
  .sort((a, b) => b.length - a.length)
  .reduce((a, c) => a.map((n, i) => n + (c[i] || 0)) || c)

// two arrays
const resultTwoArrays = sum([1, 2, 3, 4], [5, 6, 7, 8, 9])
console.log(resultTwoArrays) // [6, 8, 10, 12, 9]

// three arrays or more...
const resultThreeArrays = sum([1, 2, 3, 4], [5, 6, 7, 8, 9], [1, 2])
console.log(resultThreeArrays) // [7, 10, 10, 12, 9]
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 102
Yosvel Quintero Arguelles Avatar answered Dec 23 '25 06:12

Yosvel Quintero Arguelles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!