Created
March 12, 2020 00:10
-
-
Save ivorpad/d246c0032e9315209928e8384a120d78 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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