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

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);

Leave a Comment