Search code examples
javascriptarraysmergesum

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 corresponding keys;

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

Both arrays have unique keys, but the corresponding keys needs to be summed.

I tried loops, concat, etc but can't get the result i need.

anybody done this before?


Solution

  • 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 array
        array.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 pairs
    var results = [];
    for(var key in sums) {
        results.push([key, sums[key]]);
    }
    

    See it in action.