Skip to content Skip to sidebar Skip to footer

Javascript Merge 2 Arrays And Sum Same Key Values

I have 2 array: var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]]; var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]]; Want to get 1 merged array with the sum of cor

Solution 1:

This is one way to do it:

var sums = {}; // will keep a map of number => sum// for each input array (insert as many as you like)
[array1, array2].forEach(function(array) {
    //for each pair in that arrayarray.forEach(function(pair) {
        // increase the appropriate sum
        sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
    });
});

// now transform the object sums back into an array of pairsvar results = [];
for(var key in sums) {
    results.push([key, sums[key]]);
}

See it in action.

Solution 2:

a short routine can be coded using [].map()

var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];

array1=array2.concat(array1).map(function(a){
  var v=this[a[0]]=this[a[0]]||[a[0]];
  v[1]=(v[1]||0)+a[1];
 return this;
},[])[0].slice(1);

alert(JSON.stringify(array1)); 
//shows: [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]]

i like how it's just 3 line of code, doesn't need any internal function calls like push() or sort() or even an if() statement.

Solution 3:

The simple solution is like this.

functionsumArrays(...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

Post a Comment for "Javascript Merge 2 Arrays And Sum Same Key Values"