最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sum values of objects which are inside an array with underscore.js and reduce - Stack Overflow

programmeradmin1浏览0评论

I'm trying to sum values of objects inside and array with underscore.js and its reduce method. But it looks like I'm doing something wrong. Where's my problem?

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

I'm trying to sum values of objects inside and array with underscore.js and its reduce method. But it looks like I'm doing something wrong. Where's my problem?

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
Share Improve this question asked Feb 6, 2017 at 13:47 kirqekirqe 2,4704 gold badges40 silver badges64 bronze badges 3
  • have to return something...read the docs – charlietfl Commented Feb 6, 2017 at 13:53
  • actually, I forgot about return. But when I tried to return and display that value on html I got NaN – kirqe Commented Feb 6, 2017 at 13:55
  • 2 You forgot to give it an initial value. ..., 0) at the end of reduce. – ibrahim mahrir Commented Feb 6, 2017 at 13:58
Add a comment  | 

1 Answer 1

Reset to default 17

Use the native reduce since list is already an array.

reduce callback should return something, and have an initial value.

Try this:

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);

Note: That reduce call can be shortened even more if we omit the block and use the implicit return of the arrow function:

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

评论列表(0)

  1. 暂无评论