I have an array with a number of objects with matching keys:
[{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}]
I want to loop through the array and if the keys match I want to add the results of each and return one object with the sum of each key.
i.e.
{a: 6, b: 9, c: 6, d: 3}
The code I currently have is
function combine() {
var answer = [];
for(var i in arguments){
answer.push(arguments[i])
}
answer.reduce(function(o) {
for (var p in o)
answer[p] = (p in answer ? answer[p] : 0) + o[p];
return answer;
}, {});
}
I can find the answer here if I was to use the underscore library, however I wish to do it without using a library. I think I am having difficulty understanding how the reduce method works - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Any help as to how to solve this would be greatly appreciated. Also, I feel it is an answer that should be somewhere on SO without having to use a library.
Thanks in advance.