I know this question has been asked many times, however, unfortunately, I didn't find any answer that helped my case.
This is what my data looks like:
let data= [
{
"estimated_cost": 1.14,
"inventory_type": "power",
"cost_center_name": "Ex Hall",
},
{
"estimated_cost": 1.19,
"inventory_type": "power",
"cost_center_name": "Ex Hall",
},
{
"estimated_cost": 1.08,
"inventory_type": "fuel",
"cost_center_name": "Ex Hall",
},
{
"estimated_cost": 1.17,
"inventory_type": "power",
"cost_center_name": "Ex Hall",
},
{
"estimated_cost": 1.03,
"inventory_type": "fuel",
"cost_center_name": "Ex Hall",
},
{
"estimated_cost": 1.20,
"inventory_type": "power",
"cost_center_name": "Mac",
},
{
"estimated_cost": 1.19,
"inventory_type": "water",
"cost_center_name": "Mac",
},
{
"estimated_cost": 1.14,
"inventory_type": "power",
"cost_center_name": "Mac",
},
{
"estimated_cost": 1.18,
"inventory_type": "power",
"cost_center_name": "Ex Hall",
}
];
I want to group by two fields, inventory_type and cost_center_name, and add the values of estimated_cost.
My output should look like this:
[
{
"estimated_cost": 4.68,
"inventory_type": "power",
"cost_center_name": "Ex Hall"
},
{
"estimated_cost": 2.11,
"inventory_type": "fuel",
"cost_center_name": "Ex Hall"
},
{
"estimated_cost": 2.34,
"inventory_type": "power",
"cost_center_name": "Mac"
},
{
"estimated_cost": 1.19,
"inventory_type": "water",
"cost_center_name": "Mac"
},
]
I have this code to group by a single field and add the values, in case this helps:
export const groupBy = (data, groupByVar) => {
var array = [];
data.reduce(function (res, value) {
if (!res[value[groupByVar]]) {
let row = {};
row[groupByVar] = value[groupByVar];
row["estimated_cost"] = 0;
row["cost_center_name"] = value["cost_center_name"];
row["inventory_type"] = value["inventory_type"];
res[value[groupByVar]] = row;
array.push(res[value[groupByVar]]);
}
res[value[groupByVar]].estimated_cost += value.estimated_cost;
return res;
}, {});
return array;
};
reducereturn a new array and not mutate the existing? Either way, you define an emptyarraynamed variable, and then explicitly return that as well.