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?
a short routine can be coded using [].map()
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.
Try this:
So, the result may have holes. Just like
0
th index. Use the below function if you want to ensure there are no holes.So, you can do:
And finally if you don't want the
0
th elem ofres
. Dores.shift();
Disclaimer: I am not good with giving reasonable names.
You can use
.reduce()
to pass along an object that tracks the found sets, and does the addition.DEMO: http://jsfiddle.net/aUXLV/
If you need the result to be sorted, then add this to the end:
This is one way to do it:
See it in action.