How to combine duplicates in an array of objects and summarize a specific property?

I have this array of objects:

var arr = [ { name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 } ]; 

... and I want to combine duplicates, but summarize their contributions. The result will look like this:

 var arr = [ { name: 'John', contributions: 3 }, { name: 'Mary', contributions: 5 } ]; 

How can I achieve this using JavaScript?

+5
source share
2 answers

You can use the hash table and create a new array with the amounts you need.

 var arr = [{ name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 }], result = []; arr.forEach(function (a) { if (!this[a.name]) { this[a.name] = { name: a.name, contributions: 0 }; result.push(this[a.name]); } this[a.name].contributions += a.contributions; }, Object.create(null)); console.log(result); 
+3
source

You can also do this using the linq framework provided by linq.js

here is my code using linq.js and it is almost like sql statement.

 var arr = [ { name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 } ]; var aggregatedObject = Enumerable.From(arr) .GroupBy("$.name", null, function (key, g) { return { name: key, contributions: g.Sum("$.contributions") } }) .ToArray(); console.log(aggregatedObject); 
 <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script> 
0
source

All Articles