Skip to content
Advertisement

How to group by, calculate sum and get average in JavaScript array?

I have array of object

JavaScript

Expected result:

JavaScript

I use reduce() method to group the objects in an array by ‘group’ and calulate sum:

JavaScript

How to group object of Array by key ‘group’ and calulate average?. I tried:

JavaScript

But Expected result:

JavaScript

Advertisement

Answer

You could simply use reduce to get the total of age groups.

And use object.keys length to get the average of your total as new object from getAvg function.

Demo:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement