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 use both map and reduce in same function in javascript?

I would like to display the value 122 of amount but I don’t know how to do that.

I have this value

const products = [
  {
    id: 1,
    productM: [
      {
        product: {
          productId: 1222,
          price: {
            currency: 'EUR',
            amount: 122,
          },
        },
      },
    ],
    label: 'corner-1',
    sourceId: 23333,
  },
]

I tried this function but it’s not working and I don’t know how to do that

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

function getTotalPrice(products) {
  const arr = products.map((product) =>
    product.productM.map((p) => p.price.amount)
  );
  return arr.reduce(
    (accumulator, product) => accumulator + product,
    0
  );
}

If anyone can help, many thanks

>Solution :

I think this will work, you assumed that p was product but in reality p is the whole object, try this:

function getTotalPrice(products) {
  const arr = products.map((product) =>
    product.productM.reduce(
      (total, { product }) => total + product.price.amount,
      0
    )
  );
  return arr.reduce((accumulator, product) => accumulator + product, 0);
}

ProductM is an array so I changed it from map to a reduce, to sum all the productsM prices in it

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