I have an array with the following structure, and I am attempting to separate objects into a 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"
}
]
The desired output should be as follows;
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 are the same.
"type": "D"
},
{
"year": "202004",
"cost": 4674.59,
"type": "D"
}
]
];
Approach Attempted:
<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 achieve this data grouping? Are there any libraries or functions available for this task that I may have yet to discover? Your assistance would be greatly appreciated!