20

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?

nunoarruda
  • 2,679
  • 5
  • 26
  • 50

2 Answers2

29

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

You could also do this using linq framework which is provided by linq.js

here is my code using linq.js and this is nearly look 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>
Sanjay Radadiya
  • 1,254
  • 15
  • 22