Home > database >  Sum quantity in a lodash grouped array
Sum quantity in a lodash grouped array

Time:01-24

I have a groupedBy subscription lodash array, and I want to sum the quantity property and return the value.

Example

{
  sub_1MT4LuP6DArCazGmEdJd: [
    {
      id: 'prod_HleWjM6culM',
      quantity: 1,
    },
    {
      id: 'prod_HleWjM6culM',
      quantity: 3,
    }
  ]
}

The output should be:

{
  sub_1MT4LuP6DArCazGmEdJd: [
    {
      totalQuantity: 4,
    },
  ]
}

Which is the best way to do this sum of values in a lodash grouped array?

CodePudding user response:

You can use _.sumBy.

let o = {
  sub_1MT4LuP6DArCazGmEdJd: [
    {
      id: 'prod_HleWjM6culM',
      quantity: 1,
    },
    {
      id: 'prod_HleWjM6culM',
      quantity: 3,
    }
  ]
};
o.sub_1MT4LuP6DArCazGmEdJd = [{totalQuantity:
  _.sumBy(o.sub_1MT4LuP6DArCazGmEdJd, 'quantity')}];
console.log(o);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

  • Related