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 to group data by title in Pie Chart (Chart.js)

for example I have data

 {
  'category': 'winter',
  'amount': 10
 },
 {
  'category': 'winter',
  'amount': 10
 },
 {
  'category': 'summer',
  'amount': 10
 },
 {
  'category': 'spring',
  'amount: 10
 },
]

working (not as expected example)

https://codepen.io/Ross-Zach/pen/eYXedBr

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

So I want something like this

Pie chart that I want (SCREENSHOT)

and in legend should contains just:

winter, summer, spring

not:

winter, winter, summer, spring

>Solution :

let data = [
  { 'category': 'winter', 'amount': 10 },
  { 'category': 'winter', 'amount': 10 },
  { 'category': 'summer', 'amount': 10 },
  { 'category': 'spring', 'amount': 10 },
];

let aggregatedData = {};

  for (let i = 0; i < data.length; i++) {
  let item = data[i];
  if (aggregatedData.hasOwnProperty(item. Category)) 
  {
    aggregatedData[item.category] += item. Amount;
  } 
  else 
  {
    aggregatedData[item.category] = item. Amount;
  }
}
  • Iterate through your data array and create an object that sums the amounts for each category.

  • Use the keys of this object as the labels for the pie chart.

  • Use the sum amounts as the data for the pie chart.

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