I have 2 2d arrays
var arr1 = [
[1, 'a'],
[2, 'b']
]
var arr2 = [
[3, 'a'],
[5, 'c']
]
I would like to sum these 2 arrays to get this result
var output = [
[4, 'a'],
[2, 'b'],
[5, 'c']
]
I tried writing 2 .map functions but along with the desired results this will return a lot of duplicates:
function sumArrays (arr1, arr2) {
var output = [];
arr2.map(function(i) {
arr1.map(function(n) {
if (i[1] === n[1]) {
output.push([i[0] + n[0], i[1]])
} else {
output.push(i)
}
})
})
return output;
}
Is there an easier way to do this, or should I now be removing everything but the highest value for a specific string?
Thanks for the help.
{a : 4, b : 2, c : 5}arr1.concat(arr2).reduce((a,b)=>{return b[1] in a?a[b[1]]+=b[0]:a[b[1]]=b[0],a;},{});