Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  36] [ 1]  / answers: 1 / hits: 18303  / 8 Years ago, sun, july 10, 2016, 12:00:00

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 merge duplicates but sum their contributions. The result would be like the following:



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


How could I achieve that with JavaScript?


More From » arrays

 Answers
28

You could use a hash table and generate a new array with the sums, 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);




[#61436] Friday, July 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briannar

Total Points: 354
Total Questions: 103
Total Answers: 101

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
briannar questions
Tue, Aug 31, 21, 00:00, 3 Years ago
Sat, Jun 26, 21, 00:00, 3 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 7, 20, 00:00, 4 Years ago
;