const data = [{"label":"morning","data":[{"Amazon Prime":"0.00"},{"AppleTV":"0.00"},{"HBO Max":"25.00"},{"None":"0.00"},{"Netflix":"55.00"},{"Other":"20.00"}]},{"label":"morning","data":[{"Amazon Prime":"50.00"},{"AppleTV":"0.00"},{"HBO Max":"25.00"},{"None":"0.00"},{"Netflix":"25.00"},{"Other":"0.00"}]},{"label":"morning","data":[{"Amazon Prime":"0.00"},{"AppleTV":"0.00"},{"HBO Max":"0.00"},{"None":"50.00"},{"Netflix":"50.00"},{"Other":"0.00"}]},{"label":"afternoon","data":[{"Amazon Prime":"10.00"},{"AppleTV":"11.00"},{"HBO Max":"0.00"},{"None":"50.00"},{"Netflix":"9.00"},{"Other":"20.00"}]},{"label":"afternoon","data":[{"Amazon Prime":"0.00"},{"AppleTV":"0.00"},{"HBO Max":"5.00"},{"None":"25.00"},{"Netflix":"20.00"},{"Other":"50.00"}]}]
const groups = data.reduce((acc, { label, data }) => {
acc[label] ??= {};
data.forEach((item) => {
const [[channel, value]] = Object.entries(item);
acc[label][channel] ??= [];
acc[label][channel].push(Number(value));
});
return acc;
}, {});
// groups
//
// {"morning": {
// "Amazon Prime": [0, 50, 0"],
// "AppleTV": [0, 0, 0],
// "HBO Max": [25, 25, 0],
// "None": [0, 0, 50],
// "Netflix": [55, 25,50],
// "Other": [20, 0, 0]},
// ...}
const getFixedAvg = (data) => {
const average = data.reduce((avg, e) => avg + e) / data.length;
return (Math.floor(average * 100) / 100) // fix 16.67 to 16.66
.toFixed(2);
};
const makeData = (dataObj) => Object.entries(dataObj)
.map(([channel, dataValues]) => ({ [channel]: getFixedAvg(dataValues) }));
const result = Object.entries(groups)
.map(([label, dataObj]) => ({ label, data: makeData(dataObj) }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }