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
The _. reduce() method reduces collection to value which is accumulated result of running each element in the collection through iteratee, where each successive invocation is supplied return value of the previous. The first element of the collection is used as the initial value, if accumulator is not given.
reduce() function is an inbuilt function in Underscore. js that is used to transform an array's/object's properties into one single value or is used to create a single result from a given list of values. When all the elements of the list are passed to the function/iteratee and no more elements remains then the _.
To sum a property in an array of objects:Initialize a sum variable, using the let keyword and set it to 0 . Call the forEach() method to iterate over the array. On each iteration, increment the sum variable with the value of the object.
Here will take e.g. sum of array values using for loop, sum of array object values using javaScript reduce () method, javascript reduce array of objects by key, javascript reduce array values using javascript map () method. Follow the below examples of sum array object values with several techniques and javascript methods:
So you have an array with a bunch of values you want to sum up. To do that, we will use the reduce method. The reduce () method reduces an array and returns a single value. The reduce () method will iterate through every element in the array. We use two parameters.
The reduced method for arrays in javascript helps us specify a function called reducer function that gets called for each of the elements of an array for which we are calling that function.
Use libraries such as Lodash which has a sum function. I am a full-stack web developer with over 13 years of experience. I love learning new things and are passionate about JavaScript development both on the front-end and back-end.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With