I have an array containing quantities of votes by gender and would like to convert the quantities to percentages by gender.
The array is as follows:
genderResults: [
{ Qty: 7, Gender: 'Male', Answer: 'Badminton' },
{ Qty: 8, Gender: 'Female', Answer: 'Badminton' },
{ Qty: 2, Gender: 'Male', Answer: 'None of the above' },
{ Qty: 2, Gender: 'Female', Answer: 'None of the above' },
{ Qty: 3, Gender: 'Female', Answer: 'Rugby' },
{ Qty: 5, Gender: 'Male', Answer: 'Rugby' },
{ Qty: 4, Gender: 'Male', Answer: 'Soccer' },
{ Qty: 3, Gender: 'Female', Answer: 'Soccer' },
{ Qty: 21, Gender: 'Male', Answer: 'Squash' },
{ Qty: 16, Gender: 'Female', Answer: 'Squash' },
{ Qty: 1, Gender: 'Other', Answer: 'Squash' },
{ Qty: 18, Gender: 'Female', Answer: 'Tennis' },
{ Qty: 12, Gender: 'Male', Answer: 'Tennis' }
]
The required result would be like:
genderResults: [
{ Percentage: 47, Gender: 'Male', Answer: 'Badminton' },
{ Percentage: 53, Gender: 'Female', Answer: 'Badminton' },
{ Percentage: 50, Gender: 'Male', Answer: 'None of the above' },
{ Percentage: 50: Gender: 'Female', Answer: 'None of the above' },
{ Percentage: 37, Gender: 'Male', Answer: 'Rugby' },
{ Percentage: 63: Gender: 'Female', Answer: 'Rugby' },
...
]
I’ve tried a forEach loop and array.map but can’t figure out how to group the results?
4
Answers
Thanks @nashit-shayan - modified your code to get what I was looking for.
We can also do it with the help of reduce method but you tried it with the help of foreach method so here it is.
It can be cleaned up a bit, but I think this will fulfill your requirements. I haven’t considered any edge cases, btw.
Update:
Here you go 🙂
We can use
Array.reduce()
to group the genderResults array byAnswer.
We’ll also keep track of the total quantity for each answer and use this to calculate a percentages array for each one.
Once we have this grouped value, we can use
Object.values
and
Array.flatMap
to get the final result.