Javascript - sum 2d arrays
arrays, javascript
Solution
Please use not `Array#map`, when you do not need a new array, which this method returns.
You could use a hash table for the inventory and check against and update `arr2` with `Array#forEach`.
Proposal which uses `arr1` for update
var arr1 = [[1, 'a'], [2, 'b']],
arr2 = [[3, 'a'], [5, 'c']],
inventory = Object.create(null);
arr1.forEach(function (a) {
this[a[1]] = a;
}, inventory);
arr2.forEach(function (a) {
if (!this[a[1]]) {
this[a[1]] = [0, a[1]];
arr1.push(this[a[1]]);
}
this[a[1]][0] += a[0];
}, inventory);
console.log(arr1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Proposal with new array for `result`.
var arr1 = [[1, 'a'], [2, 'b']],
arr2 = [[3, 'a'], [5, 'c']],
inventory = Object.create(null),
result = arr1.map(function (a) {
return this[a[1]] = [a[0], a[1]];
}, inventory);
arr2.forEach(function (a) {
if (!this[a[1]]) {
this[a[1]] = [0, a[1]];
result.push(this[a[1]]);
}
this[a[1]][0] += a[0];
}, inventory);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Problem
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.