使用reduce查找数组内对象的总和

时间:2019-10-22 16:49:00

标签: node.js

我正在尝试从数组中的对象中查找总数,每个对象都有价格和数量, 当数组恰好有两个对象时,我可以找到总数,但是对于两个以上的对象,它会产生NaN

arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]


const reducer = (accumulator, currentValue) => {
    var a = accumulator.quantity * accumulator.price;
    var b = currentValue.quantity * currentValue.price;
    return a + b;
}
console.log(arr.reduce(reducer));  // sum if array contains 2 objects, NaN otherwise.

3 个答案:

答案 0 :(得分:2)

500.0

您的减速器功能似乎是错误的。累加器不再具有任何参数,因为累加器可以累加-它是整数。 另外,为累加器设置一个初始值,以从第二个参数输入中开始累加,如reduce函数所示

答案 1 :(得分:0)

arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]

const reducer = (accumulator, currentValue) {
    return accumulator + (currentValue.quantity * accumulator.price);
}

console.log(arr.reduce(reducer, 0 ));

答案 2 :(得分:0)

您可以简单地说

arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]


const total = arr.reduce((total,item)=>{
   total +=  item.quantity * item.price;
  return total
},0)