kirqe
kirqe

Reputation: 2470

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

Upvotes: 5

Views: 13206

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

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

Upvotes: 17

Related Questions