Given the following array of objects:
myArray = [
{
item: 'Item 1',
material: 'Material1',
type: 'head'
},
{
item: 'Item 1',
material: 'Material1',
type: 'head'
},
{
item: 'Item 2',
material: 'Material2',
type: 'shell'
},
{
item: 'Item 1',
material: 'Material1',
type: 'head'
},
{
item: 'Item 2',
material: 'Material2',
type: 'shell'
},
{
item: 'Item 3',
material: 'Material3',
type: 'support'
},
{
item: 'Item 1',
material: 'Material1',
type: 'head'
},
{
item: 'Item 3',
material: 'Material3',
type: 'support'
},
{
item: 'Item 2',
material: 'Material2',
type: 'shell'
}
]
I need to combine these by the item
value with a count so that I get an array that looks like this:
var myResultArray = [
{
item: 'Item 1',
material: 'Material1',
type: 'head'
count: 4
},
{
item: 'Item 2',
material: 'Material2',
type: 'shell'
count: 3
},
{
item: 'Item 3',
material: 'Material3',
type: 'support'
count: 2
},
]
What is the easiest way to do this? I'm partial to Lodash, but I'm open to other alternatives. With _.groupBy()
I can get everything grouped together with the item as the object key:
var myGrouped = _.groupBy(myArray, 'item');
but that only gets me part way there. Searching around here I see a lot of uses of _.reduce()
(or just plain .reduce()
) or _.map()
, but I haven't been able to get my head around exactly how to use them in this case. If I try to use _.groupBy()
chained with _.map()
like so
var myGrouped = _(myArray).groupBy('item').map(function(item) {
// do stuff here
});
the execution doesn't even get to my map function, so I'm not sure what I'm doing wrong.
Thanks.