Group and sum nested objects by multiple keys with loadash

Catmal :

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?

Nina Scholz :

You could sum the properies directly after grouping by 'item'.

function itemMovementbyItem(array) {
    return _(array)
        .groupBy('item')
        .map(group => ({
            item: group[0].item,
            1: _.sumBy(group, o => o.reason === 1 ? o.quantity : 0),
            2: _.sumBy(group, o => o.reason === 2 ? o.quantity : 0)
        }))
        .value();
}

var 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 }];

console.log(itemMovementbyItem(item_movements));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7289&siteId=1