5

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
3
  • have to return something...read the docs 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 Commented Feb 6, 2017 at 13:55
  • 2
    You forgot to give it an initial value. ..., 0) at the end of reduce. Commented Feb 6, 2017 at 13:58

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.