Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);
}
about 4 years ago · Juan Pablo Isaza Report

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!