0

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

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

1
  • 2
    The elements in product.productM do not have a price property. They only have a product property. Commented Nov 26, 2021 at 15:41

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of map and reduce. You can use reduce only.

Since products is nested one more level, you can use reduce twice to get it done.

Try like this.

function getTotalPrice(products) {
    return products.reduce((prev, curr) => {
        return (
            prev +
            curr.productM.reduce((innerPrev, innerCurr) => {
                return innerPrev + innerCurr.product.price.amount;
            }, 0)
        );
    }, 0);
}

Comments

0

You don't need to map anything, you can reduce directly over the original array:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.