Here is an array of objects that needs to be combined based on the item value:
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'
}
]
The desired result should look 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
},
]
How can we achieve this? Consider using Lodash's _.groupBy()
function to group by the item key:
var myGrouped = _.groupBy(myArray, 'item');
However, further steps are needed to obtain the final result. Many users suggest using _.reduce()
or _.map()
. If you attempt to combine _.groupBy()
with _.map()
, ensure proper implementation for successful execution.
Thank you.