DEV Community

Jastria Rahmat
Jastria Rahmat

Posted on • Updated on

Nested Array reduce function.

Given these:

const cart = [
    {
      products: [
        { price: 65 },
        { price: 30 }
      ]
    },
    {
      products: [
        { price: 15 },
        { price: 25 } 
      ]
    }
]
Enter fullscreen mode Exit fullscreen mode

Solution:

const totalPrice = cart.reduce((accumulator, item) => {
  const productSum = item.products.reduce((productAcc, product) => {
    return productAcc + product.price;
  }, 0);
  return accumulator + productSum;
}, 0);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)