使用 underscore.js 对数组内的对象求和并减少

Sum values of objects which are inside an array with underscore.js and reduce

我正在尝试使用 underscore.js 及其 reduce 方法对内部对象和数组的值求和。但看起来我做错了什么。我的问题在哪里?

let list = [{ title: 'one', time: 75 },
        { title: 'two', time: 200 },
        { title: 'three', time: 500 }]

let sum = _.reduce(list, (f, s) => {
    console.log(f.time); // this logs 75
    f.time + s.time
})

console.log(sum); // Cannot read property 'time' of undefined

使用原生 reduce 因为 list 已经是一个数组。

reduce回调应该return一些东西,并且有一个初始值。

试试这个:

let list = [{ title: 'one', time: 75 },
        { title: 'two', time: 200 },
        { title: 'three', time: 500 }];

let sum = list.reduce((s, f) => {
    return s + f.time;               // return the sum of the accumulator and the current time, as the the new accumulator
}, 0);                               // initial value of 0

console.log(sum);

注意:如果我们省略块并使用箭头函数的隐式return,reduce调用可以缩短更多:

let sum = list.reduce((s, f) => s + f.time, 0);