I have a array like this in below, What I'm trying is seperating objects to new array by grouping two values.
Array:
[
{
"year": "202003",
"cost": 11194.55,
"type": "A"
},
{
"year": "202003",
"cost": 60.2,
"type": "B"
},
{
"year": "202003",
"cost": 747.12,
"type": "C"
},
{
"year": "202003",
"cost": 747.12,
"type": "D"
},
{
"year": "202004",
"cost": 747.12,
"type": "D"
},
{
"year": "202003",
"cost": 4674.59,
"type": "D"
}
]
Result should be like this;
Output
[
[
{
"year": "202003",
"cost": 11194.55,
"type": "A"
}
],
[
{
"year": "202003",
"cost": 60.2,
"type": "B"
}
],
[
{
"year": "202003",
"cost": 747.12,
"type": "C"
}
],
[
{
"year": "202003",
"cost": 1494.24, // sum of the COST value when year and type same.
"type": "D"
},
{
"year": "202004",
"cost": 4674.59,
"type": "D"
}
]
];
What I've tried
<script src="//cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
let aggregatedObject = Enumerable.From(data)
.GroupBy("$.type", "$.year",
function (key, g) {
return {
label: key,
value: g.Sum("$.cost"),
}
})
.ToArray();
How can I group this data like this? Is there any library or a function to do this? I couldn't find yet. Any help will be highly appreciated!