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

How to sum multiplication values from objects in an array?

if i have an array that looks like this :

    "orderItems": [
  {
    "description": "Test",
    "identifier": "Test identifier",
    "priceCent": 1,
    "lengthIn": 10,
    "widthIn": 5,
    "heightIn": 10,
    "weightLbs": 3,
    "quantity": 2
  },
{
    "description": "Test-2",
    "identifier": "Test identifier",
    "priceCent": 1,
    "lengthIn": 10,
    "widthIn": 5,
    "heightIn": 10,
    "weightLbs": 4,
    "quantity": 3
  }
]

How can I multiply weightLbs and quantity and sum those within the objects?
For example:

3 * 2 = 6
4 * 3 = 12

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

and result total I want is = 18

This is what I have so far, but this only adds weightLbs

        return delivery.order.orderItems.reduce((prev, curr) => {
      return prev + (curr.totalWeightLbs || 0);
    }, 0);

>Solution :

orderItems.reduce((sum, currentItem) => { 
    return sum + (currentItem.weightLbs * currentItem.quantity); 
}, 0);

this will multiply the values and sum them in the reduce accumulator

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