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
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.