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
|
1 Answer
Reset to default 17Use 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)
at the end ofreduce
. – ibrahim mahrir Commented Feb 6, 2017 at 13:58