I have an array of objects lets say data. I want to group this array of objects based on another array lets say arr and also get the accumulated count and get the output for each of the array elements as key. The data variable
const data = [
{
"a":"A1",
"b":"B2",
"c": "C1",
"count": 10
},
{
"a":"A1",
"b":"B1",
"c": "C2",
"count": 20
},
{
"a":"A1",
"b":"B2",
"c": "C1",
"count": 50
},
{
"a":"A2",
"b":"B1",
"c": "C2",
"count": 60
},
{
"a":"A2",
"b":"B2",
"c": "C2",
"count": 30
},
];
The arr variable
const arr = ["a","b","c"];
The result output should be
const result = [
[
{
"key":"a",
"value":"A1",
"count": 80
},
{
"key":"a",
"value":"A2",
"count": 90
}
],
[
{
"key":"b",
"value":"B1",
"count": 80
},
{
"key":"b",
"value":"B2",
"count": 90
}
],
[
{
"key":"c",
"value":"C1",
"count": 60
},
{
"key":"c",
"value":"C2",
"count": 110
}
]
];
I tried the below function but I am not able to group and get accumulated count.
const groupBy = (array, key) => {
return key.map(keyl => {
return array.reduce((result, currentValue) => {
(result[keyl] = result[keyl]|| []).push(
{"key":keyl,"value": currentValue[keyl],"count":currentValue["count"]}
);
return result;
}, {});
})
};
const groupByAndCount = groupBy(data, arr);
console.log("groupByAndCount",groupByAndCount)