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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[使用reduce查找数组内对象的总和相关的知识,希望对你有一定的参考价值。

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

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

    let reducer = (acc, cur) => {
     return acc + (Number(cur.quantity) * Number(cur.price));
    };

    console.log(arr.reduce(reducer, 0));
    // 100
另一答案
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 ));
另一答案

您可以简单地说

以上是关于[使用reduce查找数组内对象的总和的主要内容,如果未能解决你的问题,请参考以下文章