Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum quantity in a lodash grouped array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading