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?

3
  • 2
    Have you tried anything so far? Commented Jul 10, 2016 at 17:47
  • 1
    jsfiddle.net/mplungjan/Lr84keqy Commented Jan 2, 2019 at 13:06
  • In my case, cosnt res = new Set(array1, array2) works perfect. Commented Sep 22, 2019 at 11:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

You can use the brand new ES6 Map object : var result = new Map(); arr.forEach((element) => { if (result.get(element.name)) result.set(element.name, result.get(element.name) + element.contributions); else result.set(element.name, element.contributions); }); console.log(result);
-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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.