In the array below, I want to group by item and reason then calculate the total quantity:
item_movements = [
{
item: "Apple",
reason: 1,
quantity: 5
},
item: "Banana",
reason: 2,
quantity: 10
},
{
item: "Apple",
reason: 1,
quantity: 5
},
item: "Banana",
reason: 1,
quantity: 8
},
{
item: "Apple",
reason: 2,
quantity: 3
},
item: "Banana",
reason: 1,
quantity: 8
}
]
The result am trying to achieve is this:
item_totals = [
{
item: "Apple",
1: 10,
2: 3
},
{
item: "Banana",
1: 16,
2: 10
}
I was able to group by item using loadash like so:
itemMovementbyItem() {
var result = _(this.item_movements)
.groupBy(x => x.item)
.map((value, key) => ({
item: key,
item_movements: value
}))
.value()
return result
},
But I am having problems to group a second time by reason.
Any suggestion?