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?
To merge duplicate objects in array of objects with JavaScript, we can use the array map method. to merge the items with the label value together. To do this, we get an array of labels without the duplicates with [... new Set(data.
To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With