I have an array with a number of objects with the corresponding keys:
[{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}]
I want to iterate over the array and, if the keys match, I want to add the results of each of them and return one object with the sum of each key.
i.e.
{a: 6, b: 9, c: 6, d: 3}
In my code there 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 had to use the underscore library, however I want to do this without using the library. I think I hardly understand how the reduce
method works - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Any help regarding how to solve this problem would be greatly appreciated. Also, I believe this is an answer that should be somewhere in SO without having to use a library.
Thanks in advance.
user6002037
source share