简体   繁体   English

我如何使用JS中的reduce函数计算购物袋中商品的总价

[英]How may I calculate the total price of goods from the shopping bag using reduce function in JS

const goods = {
    "Bread": {
        price: 3,
        discount: 10,
    },
    "Milk": {
        price: 1,
        discount: 5,
    },
};

const shoppingBag = [
    { product: 'Milk', quantity: 5 },
    { product: 'Bread', quantity: 13 },
];

I need to get the sum of goods in the shoppingBag .我需要获取shoppingBag的商品总和。 I guess I should use reduce() but I don't know how values from goods move to shoppingBag.我想我应该使用reduce()但我不知道商品的价值如何转移到shoppingBag。 Could you help?你能帮忙吗?

I just got keys and values from goods:我刚刚从商品中获得了键和值:

const goodsNames = Object.keys(goods);
const goodsPrices = Object.values(goods);

There is a certain amount of information that your question is missing that will make a full answer difficult.您的问题缺少一定数量的信息,这将使完整的答案变得困难。 I've made some assumptions.我做了一些假设。 The biggest assumption is that the discount is a percent that would be applied to the total of each item.最大的假设是折扣是应用于每个项目总数的百分比。 To be clear, this could all be done in one reduce function as you suggest, but I find it easier to understand if broken up into smaller functions.需要明确的是,这一切都可以按照您的建议在一个 reduce 函数中完成,但我发现如果分解成更小的函数更容易理解。 I'm using map to take each product in the shopping cart and return the total amount for that product.我正在使用地图来获取购物车中的每个产品并返回该产品的总金额。 Reduce is used at the end to sum up the total of all of the products in the cart. Reduce 用于最后总结购物车中所有产品的总数。

 const goods = { "Bread": { price: 3, discount: 10, }, "Milk": { price: 1, discount: 5, }, }; const shoppingBag = [ {product: 'Milk', quantity: 5}, {product: 'Bread', quantity: 13}, ]; console.log( shoppingBag .map(item => { // get the items pricing information by looking it up in the object based off of its key. var itemPricing = goods[item.product]; // calculate the gross total amount for the item before applying the discount var itemGrossTotal = item.quantity * itemPricing.price; // make the percentage into a decimal and apply the discount to the gross total return itemGrossTotal * ((100 - itemPricing.discount)/100); }) // sum the discounted price of all of the products .reduce((item1, item2) => item1 + item2, 0) );

I have an ideal.我有一个理想。 First need to collection in map and have to do reduce首先需要在地图中收集并且必须做reduce

    var total = shoppingBag.map(item=>{
        return goods[item.product].price*item.quantity;
    }).reduce((total,num)=>{
        return total+num;
    })
console.log(total)

you can use this你可以用这个

update the calculation as need根据需要更新计算

shoppingBag.reduce((accumulator, current) => {
// current is the current iteration of the array

   const itemPricingObj = goods[current.product];

// do the math as you want
// but i will just get total Price

   return accumulator + ((itemPricingObj.price * current.quantity) - (itemPricingObj.discount * itemPricingObj.price ))

}, 0); // 0 is the initial value of the accumulator

Assuming discount is in percentage, this can do the job假设折扣是百分比,这可以完成工作

function calculate() {
    const goods = {
        "Bread": {
            price: 3,
            discount: 10,
        },
        "Clothes": {
            price: 40,
            discount: 8
        },
        "Milk": {
            price: 1,
            discount: 5,
        },
    };
    
    
    const shoppingBag = [
        { product: 'Bread', quantity: 13 },
        { product: 'Milk', quantity: 5 },
        { product: 'Clothes', quantity: 5 },
    ];

    const totalSum = shoppingBag.reduce((prev, current) => {
        const totalPrice = goods[current.product].price * current.quantity;
        const discount = goods[current.product].discount;
        const netPrice = totalPrice * (100 - discount) / 100;
        return prev + netPrice;
    }, 0);

    console.log(totalSum);

}

I feel this would be a lot cleaner, what do you think?我觉得这样会干净很多,你觉得呢?

const getDiscountedPrice = (price, discount) => {
  return Math.round(
    price * (1 - (discount/100))
  );
}

const calculateTotalPrice = (shoppingBag, goods) => shoppingBag.reduce((totalPrice, bagItem) => {
  const { product, quantity} = bagItem;
  const productDetails = goods[product];
  // Check if the item in the `shoppingBag` exists in `goods`
  if (productDetails) {
    const { price, discount } = productDetails;
    totalPrice += (quantity * getDiscountedPrice(price, discount));
  }
  return totalPrice;
}, 0);

console.log('Total amount pending: ', calculateTotalPrice(shoppingBag, goods));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM