Skip to content

Instantly share code, notes, and snippets.

@ivorpad
Created March 12, 2020 00:10
Show Gist options
  • Save ivorpad/d246c0032e9315209928e8384a120d78 to your computer and use it in GitHub Desktop.
Save ivorpad/d246c0032e9315209928e8384a120d78 to your computer and use it in GitHub Desktop.
const generatePieChartData = (data, percentages = false, keys = []) => {
const isSingleArray = Object.keys(data).length <= 1;
if (isSingleArray) {
return Object.entries(data).reduce((acc, [key, data], idx) => {
keys.forEach((k, i) => {
acc[i] = {
id: k,
label: k,
value: data[i]
};
});
return acc;
}, []);
} else {
const total = Object.values(data)
.flat()
.map(v => Number(v))
.reduce((acc, curr) => acc + curr);
return Object.entries(data).reduce((acc, [key, data], idx) => {
// TODO: Return error if values are not number
acc[idx] = {
id: key,
label: key,
value: percentages
? +(
(data.map(v => +v).reduce((acc, curr) => acc + curr) * 100) /
total
).toFixed(2)
: +data.map(v => +v).reduce((acc, curr) => acc + curr)
};
return acc;
}, []);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment