I have an array of objects like below for example.
{name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
I want to group them up and adding up all the values in it. For example, the final would be like this:
{name: "Mc Donald", quantity: 8, maleCount: 1, femaleCount: 1}
{name: "KFC", quantity: 54, maleCount: 3, femaleCount: 3}
How can I achieve this in JavaScript?
I have tried to find some solution online but it is not the one I wanted. For example this solution
My solution based on reduce:
hope this will help
You can use array reduce:
check this code below:
You can use
forEach()
loop and add to new array. You can pass empty object asthisArg
parameter that you can use asthis
in your callback function and in second forEach context ofthis
will still be the same as in first callback function because of arrow function.Here is a generic solution that uses clean and modern JavaScript:
You could group with a hash table and use an array for the keys with variable values.
With linq.js