# Merge objects with the same id but sum values of the objects (ok)

## [Merge objects with the same id but sum values of the objects](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects)

[Ask Question](https://stackoverflow.com/questions/ask)Asked 5 years, 7 months agoModified [5 years, 7 months ago](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects?lastactivity)Viewed 3k times1

I want to reduce my array of objects by comparing previous and current object from the array, if the id of previous object is different then current object, then I write the previous object to my result list and override it with the current object else I sum the values of both objects. In the end it should be a reduced array, no duplicates.

I have data like this:

```javascript
[{
    Clicks: 210,
    Company: "A",
    _id: { CompanyID: 5 }
},
{
    Clicks: 35,
    Company: "C",
    _id: { CompanyID: 3 }
},
{
    Clicks: 15,
    Company: "B",
    _id: { CompanyID: 2 }
},
{
    Clicks: 13,
    Company: "A",
    _id: { CompanyID: 5 }
}]
```

And want to reduce it to this form:

```javascript
[{
    Clicks: 223,
    Company: "A",
    _id: { CompanyID: 5 }
},
{
    Clicks: 35,
    Company: "C",
    _id: { CompanyID: 3 }
},
{
    Clicks: 15,
    Company: "B",
    _id: { CompanyID: 2 }
}]
```

Here is my not correctly working solution so far:

```javascript
$scope.reduce = function () {
    var result = [];
    var prev = null;

    angular.forEach($scope.data, function (value, key) {
        if (prev != null) {
            if (prev._id.CompanyID != value._id.CompanyID) {
                result.push(prev);
                prev = value;
            } else {
                prev.Clicks += value.Clicks;
            }
        } else {
            prev = value;
        }
    });
}
```

My result looks good, it reduce all duplicates but it does not sum the values of objects with the same ids, it just overrides the ids with the last object.

* [javascript](https://stackoverflow.com/questions/tagged/javascript)
* [group-by](https://stackoverflow.com/questions/tagged/group-by)
* [reduce](https://stackoverflow.com/questions/tagged/reduce)

[Share](https://stackoverflow.com/q/44332180)[Improve this question](https://stackoverflow.com/posts/44332180/edit)Follow[edited Jun 2, 2017 at 15:19](https://stackoverflow.com/posts/44332180/revisions)[![Emile Bergeron's user avatar](https://www.gravatar.com/avatar/75c6b54df38abce7b1c35f499a1d4a67?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/1218980/emile-bergeron)[Emile Bergeron](https://stackoverflow.com/users/1218980/emile-bergeron)16.7k44 gold badges8181 silver badges125125 bronze badgesasked Jun 2, 2017 at 15:12[![Rep's user avatar](https://www.gravatar.com/avatar/dd2dee0ccaa9b753daefaa2828d526ed?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/669539/rep)[Rep](https://stackoverflow.com/users/669539/rep)10933 silver badges1313 bronze badges[Add a comment](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects#)

### 2 Answers

Sorted by:                                              Highest score (default)                                                                   Trending (recent votes count more)                                                                   Date modified (newest first)                                                                   Date created (oldest first)                              5

You can use `thisArg` parameter in `forEach` loop and pass a empty object to store values.

```javascript
var data = [{"Clicks":210,"Company":"A","_id":{"CompanyID":5}},{"Clicks":35,"Company":"C","_id":{"CompanyID":3}},{"Clicks":15,"Company":"B","_id":{"CompanyID":2}},{"Clicks":13,"Company":"A","_id":{"CompanyID":5}}];
var result = [];

data.forEach(function(obj) {
  var id = obj._id.CompanyID
  if(!this[id]) result.push(this[id] = obj);
  else this[id].Clicks += obj.Clicks;
}, Object.create(null));

console.log(result);
```

&#x20;Run code snippetExpand snippet[Share](https://stackoverflow.com/a/44332320)[Improve this answer](https://stackoverflow.com/posts/44332320/edit)Follow[edited Jun 2, 2017 at 15:24](https://stackoverflow.com/posts/44332320/revisions)[![Emile Bergeron's user avatar](https://www.gravatar.com/avatar/75c6b54df38abce7b1c35f499a1d4a67?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/1218980/emile-bergeron)[Emile Bergeron](https://stackoverflow.com/users/1218980/emile-bergeron)16.7k44 gold badges8181 silver badges125125 bronze badgesanswered Jun 2, 2017 at 15:19[![Nenad Vracar's user avatar](https://i.stack.imgur.com/BuWrj.jpg?s=64\&g=1)](https://stackoverflow.com/users/4620771/nenad-vracar)[Nenad Vracar](https://stackoverflow.com/users/4620771/nenad-vracar)116k1515 gold badges146146 silver badges169169 bronze badges

* Thanks for you help. I actually wanted to know what my mistake was. I already found out what i did wrong, i have logic error, because i reference to my first object instead of doing a deep copy. And your code is somewhat irritating by using the keyword this. I think it is not good to use this in javascript, specially here. :) – [Rep](https://stackoverflow.com/users/669539/rep) [Jun 2, 2017 at 21:13](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects#comment75678963_44332320)&#x20;
* `I think it is not good to use this in javascript` why is that? – [Nenad Vracar](https://stackoverflow.com/users/4620771/nenad-vracar) [Jun 2, 2017 at 21:40](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects#comment75679531_44332320)&#x20;
* In your example "this" is irritating, but it works fine, but not a good design from my point. It is not clear what "this" actually is. So for me and a lot of other developer will agree that "this" can be confusing ("this" in object scope or object's function scope?) and bring inconsistent behavior. Here is how i changed your code: [link](https://jsfiddle.net/pt8e6op6/) – [Rep](https://stackoverflow.com/users/669539/rep) [Jun 3, 2017 at 10:07](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects#comment75688453_44332320)

[Add a comment](https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects#)4

For a version with [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), you could use a hash table as reference to the same company with a closure over the hash table.

```javascript
var data = [{ Clicks: 210, Company: "A", _id: { CompanyID: 5 } }, { Clicks: 35, Company: "C", _id: { CompanyID: 3 } }, { Clicks: 15, Company: "B", _id: { CompanyID: 2 } }, { Clicks: 13, Company: "A", _id: { CompanyID: 5 } }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var key = a._id.CompanyID;
            if (!hash[key]) {
                hash[key] = { Clicks: 0, Company: a.Company, _id: a._id };
                r.push(hash[key]);
            }
            hash[key].Clicks += a.Clicks;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);
```

```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```

## [How to sum the array of object values and assigned them to the relevant key name](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name)

## [How to sum the array of object values and assigned them to the relevant key name](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name)

[Ask Question](https://stackoverflow.com/questions/ask)Asked 12 months agoModified [3 months ago](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name?lastactivity)Viewed 3k times2

I need to understand the simplest way of doing this. I've got an array of objects:

```javascript
const data = [
  {
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
]
```

What I'm trying to get is simple object where its key is the month from data.incomes and the value is sum of relative month values, so the final result looks like:

```javascript
const totalIncomes = {
  "2019-12": 125,
  "2020-12": 250,
  "2021-12": 15
}
```

Can anybody explain it to me step by step, please?

* [javascript](https://stackoverflow.com/questions/tagged/javascript)
* [arrays](https://stackoverflow.com/questions/tagged/arrays)
* [object](https://stackoverflow.com/questions/tagged/object)
* [filtering](https://stackoverflow.com/questions/tagged/filtering)

[Share](https://stackoverflow.com/q/70790223)[Improve this question](https://stackoverflow.com/posts/70790223/edit)Followasked Jan 20, 2022 at 16:52[![dariusz's user avatar](https://www.gravatar.com/avatar/60dfb1e640dd27078d84986a738432a7?s=64\&d=identicon\&r=PG\&f=1)](https://stackoverflow.com/users/6523359/dariusz)[dariusz](https://stackoverflow.com/users/6523359/dariusz)33711 gold badge33 silver badges1414 bronze badges[Add a comment](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#)

### 4 Answers

Sorted by:                                              Highest score (default)                                                                   Trending (recent votes count more)                                                                   Date modified (newest first)                                                                   Date created (oldest first)                              3

solved using reduce and forEach

Inside the reduce function I'm running a `forEach` on the array of keys of the `incomes` object/attribute. For each key which is a date I'm checking if the accumulator of the reduce function contains an attribute for each date and creates if not. After creating the attribute I'm summing the value for the current date attribute.

```javascript
const data = [{
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
]

const totalIncomes = data.reduce((acc, curr) => {
  Object.keys(curr.incomes).forEach((key, index) => {
    if (!acc[key]) {
      acc[key] = 0
    }
    acc[key] += curr.incomes[key]
  })
  return acc
}, {})

console.log(totalIncomes)
```

&#x20;Run code snippetExpand snippet[Share](https://stackoverflow.com/a/70790308)[Improve this answer](https://stackoverflow.com/posts/70790308/edit)Follow[edited Sep 30, 2022 at 15:49](https://stackoverflow.com/posts/70790308/revisions)answered Jan 20, 2022 at 16:57[![cmgchess's user avatar](https://i.stack.imgur.com/myTpQ.jpg?s=64\&g=1)](https://stackoverflow.com/users/13583510/cmgchess)[cmgchess](https://stackoverflow.com/users/13583510/cmgchess)5,0883333 gold badges4141 silver badges5151 bronze badges

* 1Thanks a lot! I tried to do almost the same using Object.entries() not Object.keys and that was where I had an error coming from. – [dariusz](https://stackoverflow.com/users/6523359/dariusz) [Jan 20, 2022 at 17:01](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#comment125146536_70790308)
* 1\@cmgchess this answer can be improved by adding some useful explanation... – [Gass](https://stackoverflow.com/users/14895985/gass) [Jan 21, 2022 at 6:45](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#comment125158959_70790308)
* 1\@Gass i was in a hurry. added some explanation – [cmgchess](https://stackoverflow.com/users/13583510/cmgchess) [Jan 21, 2022 at 13:59](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#comment125168000_70790308)

[Add a comment](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#)1

Maybe this is not the pretties solutions but you can do it like this, the function is of course not necessary.

```javascript
const data = [
  {
    group: "A",
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15,
    },
  },
  {
    group: "B",
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    },
  },
];

getterInformation(data);

function getterInformation(object) {
  let objectWithCalculatedValues = {};

  object.forEach((items) => {
    for (const key in items.incomes) {
      if (objectWithCalculatedValues[key] === undefined) {
        objectWithCalculatedValues[key] = 0;
      }

      objectWithCalculatedValues[key] += items.incomes[key];
    }
  });

  console.log(objectWithCalculatedValues);
}
```

[Share](https://stackoverflow.com/a/70790505)[Improve this answer](https://stackoverflow.com/posts/70790505/edit)Followanswered Jan 20, 2022 at 17:11[![Galterius's user avatar](https://i.stack.imgur.com/TkleU.jpg?s=64\&g=1)](https://stackoverflow.com/users/9821521/galterius)[Galterius](https://stackoverflow.com/users/9821521/galterius)8911 silver badge33 bronze badges

* Maybe it's not the prettiest on but it's working and it's also easy for me to understand so it's absolutely fine.👍 Thank you. – [dariusz](https://stackoverflow.com/users/6523359/dariusz) [Jan 20, 2022 at 17:18](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#comment125146930_70790505)
* @Galterius you can improve it easily by reducing the length of your variable names. They should be descriptive but not that much ;) – [Gass](https://stackoverflow.com/users/14895985/gass) [Jan 20, 2022 at 19:20](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#comment125149809_70790505)&#x20;
* 1I know, sometime I have problem naming vars :)))) – [Galterius](https://stackoverflow.com/users/9821521/galterius) [Jan 20, 2022 at 20:33](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#comment125151412_70790505)

[Add a comment](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#)1

Assuming that this information may be useful to readers who may be unable to obtain necessary guidance (due to various possible reasons), here is one possible way to achieve the objective (solution):

```javascript
const aggregateIncomesByMonth = () => (
  data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
    key: k,
    value: v
  }))).flat().reduce((fin, itm) => ({
    ...fin,
    [itm.key]: (fin[itm.key] || 0) + itm.value
  }), {})
);
```

**Explanation**

1. Extract only the `incomes` from the `data` array
2. For each `income` object, get the key-value pair and transform into another object of the structure `{key: 20yy-mm, value: nn}`
3. Use `.flat()` to transform the result from step-2 into a 1-dimensional array
4. Use `.reduce` to sum the `value` for those cases where the `key` (ie, 20yy-mm) matches.

**Code-snippet**

```javascript
const data = [{
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
];

const aggregateIncomesByMonth = () => (
  data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
    key: k,
    value: v
  }))).flat().reduce((fin, itm) => ({
    ...fin,
    [itm.key]: (fin[itm.key] || 0) + itm.value
  }), {})
);

console.log(aggregateIncomesByMonth());
```

&#x20;Run code snippetExpand snippet[Share](https://stackoverflow.com/a/70790704)[Improve this answer](https://stackoverflow.com/posts/70790704/edit)Followanswered Jan 20, 2022 at 17:25[![jsN00b's user avatar](https://i.stack.imgur.com/wU5Nw.png?s=64\&g=1)](https://stackoverflow.com/users/13658816/jsn00b)[jsN00b](https://stackoverflow.com/users/13658816/jsn00b)3,53922 gold badges77 silver badges2121 bronze badges[Add a comment](https://stackoverflow.com/questions/70790223/how-to-sum-the-array-of-object-values-and-assigned-them-to-the-relevant-key-name#)1

My approach here is to destructure the array. This way I have all the data of the incomes of group A in the variable `A` and the same for `B`.

Then I do a double loop to compare both objects data and see if the dates match. If so, sum the incomes and add the data to the `total` object.

```javascript
const data = [
  {
    group: 'A',
    incomes: { "2019-12": 100, "2020-12": 200, "2021-12": 15 }
  },
  {
    group: 'B',
    incomes: { "2019-12": 25, "2020-12": 50 }
  }
]

let A, B, total = {};

[A, B] = [data[0].incomes, data[1].incomes]

for(const date in A){
  for(const d in B){
   total[date] = date === d ? A[date] + B[date] : A[date]
  }  
}

console.log(total)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/advanced/javascript/merge-objects-with-the-same-id-but-sum-values-of-the-objects-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
