简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM