Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge duplicates in an array of objects and sum a specific property? [duplicate]

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?

like image 928
nunoarruda Avatar asked Jul 10 '16 17:07

nunoarruda


People also ask

How do you merge duplicate values in an array of objects?

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.

How do you remove duplicate objects from an array of objects?

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.


1 Answers

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);
like image 89
Nina Scholz Avatar answered Oct 17 '22 01:10

Nina Scholz