Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the sum of of Similar array object values and separate them based on their values

I have the following array object

  [{ count: 2, created_data: "2022 07 19" },
  { count: 4, created_data: "2022 07 19" },
  { count: 4, created_data: "2022 07 19" },
  { count: 1, created_data: "2022 07 20" },
  { count: 1, created_data: "2022 07 20" }]

I would want to add the objects and get their sums based on the dates. So the result should look something like this

[{
  "2022 07 19" : 10,
  "2022 07 20" : 2
}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just group by the desired property using reduce method.

var data = [{ count: 2, created_data: "2022 07 19" },
  { count: 4, created_data: "2022 07 19" },
  { count: 4, created_data: "2022 07 19" },
  { count: 1, created_data: "2022 07 20" },
  { count: 1, created_data: "2022 07 20" }]
  
var result = [data.reduce(function(agg, item) {
  agg[item.created_data] = (agg[item.created_data] || 0) + item.count
  return agg
}, {})]

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading