首页 > 解决方案 > 使用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.

标签: node.js

解决方案


    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

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


推荐阅读