Home > Software engineering >  How to use both map and reduce in same function in javascript?
How to use both map and reduce in same function in javascript?

Time:11-27

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

CodePudding user response:

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

CodePudding user response:

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);
}

CodePudding user response:

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);
}
  • Related