I'm trying to find the easiest way to take an array that has like information and create an array with sub array. The newly created parent array should also sum the values that are found in the sub-array. This is the equivalent of an SQL statement that uses sum/group by.
This is the original array
[
{
'userId':1,
'userName':'bob',
'category':'shoes',
'count':2
},
{
'userId':1,
'userName':'bob',
'category':'rocks',
'count':4
},
{
'userId':1,
'userName':'bob',
'category':'bags',
'count':3
},
{
'userId':2,
'userName':'sue',
'category':'shoes',
'count':1
},
{
'userId':2,
'userName':'sue',
'category':'rocks',
'count':7
},
{
'userId':2,
'userName':'sue',
'category':'bags',
'count':4
},
]
This is what I want the newly created array to look like:
[
{
'userId':1,
'userName':'bob',
'purchases': [
{'category':'shoes','count':'2'},
{'category':'rocks','count':'4'},
{'category':'bags','count':'3'}
],
'totalCount' : 9
},
{
'userId':2,
'userName':'sue',
'purchases': [
{'category':'shoes','count':'1'},
{'category':'rocks','count':'7'},
{'category':'bags','count':'4'}
],
'totalCount' : 12
},
]