【问题标题】:How to count the sum of values in an array of objects in JavaScript?如何计算 JavaScript 中对象数组中值的总和?
【发布时间】:2020-02-11 14:21:48
【问题描述】:

这是一个如此简单的任务,但不知何故我被卡住了。我有一个如下所示的产品对象数组:

[{id: 1, price: 30, quantity: 2}, {id: 2, price: 20, quantity: 4}, {id: 3, price: 10, quantity: 2}]

我需要计算所有商品的总价格,应该是:特定产品的价格乘以数量,与之前的产品相同。示例:(30*2)+(20*4)+(10*2)

我的代码如下所示:

    items.forEach(function (item) {
           let sum = item.price * item.quantity;
           console.log(sum);
});

输出如下:

60
80
20

但我需要计算应该是 160 的总数并将其呈现到页面上,但不知何故我无法弄清楚如何做到这一点

【问题讨论】:

  • 所以把你的let sum移到for循环之外......说真的,你离自己解决这个问题只有一步之遥。
  • 你需要使用 JavaScript 中的 reduce 函数。
  • .reduce((p, { price, quantity }) => p + price*quantity, 0)
  • 我注意到您没有在代码中的任何地方使用+;如果您尝试计算总和,这是一个不好的迹象。
  • @Taplar:至少一步,但不仅仅是将let sum移出循环。

标签: javascript


【解决方案1】:

Array.prototype.reduce() 方法最适合这样的操作(总计)。

在我下面的回答中,sum 是累加器,最初设置为 0。累加器是回调之前返回的值。 { price, quantity } 是当前值的object destructering。

const sumTotal = arr =>
  arr.reduce((sum, { price, quantity }) => sum + price * quantity, 0)

const data = [
  { id: 1, price: 30, quantity: 2 },
  { id: 2, price: 20, quantity: 4 },
  { id: 3, price: 10, quantity: 2 },
]

const total = sumTotal(data)

console.log(total) // 160

这是一个类似的example。

【讨论】:

  • 这是一个类似的example。 sum 是累加器,初始设置为 0。{ price, quantity } 是当前值的object destructering。每一步回调的返回值成为下一步的累加器(sum)值。
【解决方案2】:

您即将得到答案。我稍微修改了您的代码并获得了预期的结果。见下文。

const items = [{id: 1, price: 30, quantity: 2}, {id: 2, price: 20, quantity: 4}, {id: 3, price: 10, quantity: 2}];

const sumItems = () => {
let sum = 0;
items.forEach(function(item) {
    let calculation = item.price * item.quantity;
    sum += calculation;
})
console.log(sum);
};

sumItems();

【讨论】:

    【解决方案3】:

    let items = [
      {id: 1, price: 30, quantity: 2}, 
      {id: 2, price: 20, quantity: 4}, 
      {id: 3, price: 10, quantity: 2}
    ]
    
    let total = items.reduce((sum,item) => sum + item.price * item.quantity, 0);
    
    console.log(total);

    【讨论】:

      【解决方案4】:

      var products =[{id: 1, price: 30, quantity: 2}, {id: 2, price: 20, quantity: 4}, {id: 3, price: 10, quantity: 2}]
      console.log(products.map(x=> x.price*x.quantity).reduce((a, b) => a + b, 0))

      【讨论】:

        【解决方案5】:

        如果你可以使用外部库,我建议使用lodashlibrary中的sumBy方法

        例子:

        _.sumBy(items, function(item) { return item.price * item.quantity; });
        

        【讨论】:

          猜你喜欢
          • 2017-01-17
          • 1970-01-01
          • 1970-01-01
          • 2018-11-01
          • 1970-01-01
          • 2018-08-05
          • 1970-01-01
          • 2021-10-26
          • 1970-01-01
          相关资源
          最近更新 更多