Sum Values of Properties Inside Array of Custom Objects Using Reduce

Sum values of properties inside array of custom objects using reduce

It simply like this

let sum = array.reduce(0) { $0 + $1.value }

How to call reduce on an array of objects to sum their properties?

After the first iteration your're returning a number and then trying to get property x of it to add to the next object which is undefined and maths involving undefined results in NaN.

try returning an object contain an x property with the sum of the x properties of the parameters:

var arr = [{x:1},{x:2},{x:4}];

arr.reduce(function (a, b) {
return {x: a.x + b.x}; // returns object with property x
})

// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));

// -> {x: 7}

Explanation added from comments:

The return value of each iteration of [].reduce used as the a variable in the next iteration.

Iteration 1: a = {x:1}, b = {x:2}, {x: 3} assigned to a in Iteration 2

Iteration 2: a = {x:3}, b = {x:4}.

The problem with your example is that you're returning a number literal.

function (a, b) {
return a.x + b.x; // returns number literal
}

Iteration 1: a = {x:1}, b = {x:2}, // returns 3 as a in next iteration

Iteration 2: a = 3, b = {x:2} returns NaN

A number literal 3 does not (typically) have a property called x so it's undefined and undefined + b.x returns NaN and NaN + <anything> is always NaN

Clarification: I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner. It may result in fewer lines written but imo it is less readable.

is it possible to sum up the properties of an array of objects and to filter it according to another property?

I'd suggest using Array.reduce() to group dates and visitors by page.

We'd sort the input array to ensure our output is also sorted by date.

The accumulator (acc) will have a property for each page, with a page name, a list of dates and number of visits array.

We'd use Object.values() to get the final array required.





const a = [{ "page": "Page 1", "date": "2021-10-05", "visitors": 10 }, { "page": "Page 2", "date": "2021-10-05", "visitors": 20 }, { "page": "Page 3", "date": "2021-10-05", "visitors": 30 },{ "page": "Page 1", "date": "2021-10-04", "visitors": 40 }, { "page": "Page 2", "date": "2021-10-04", "visitors": 50 }, { "page": "Page 3", "date": "2021-10-04", "visitors": 60 }]

const sortByDate = ({ date: a}, { date:b }) => Date.parse(a) - Date.parse(b);

const result = Object.values(a.sort(sortByDate).reduce((acc, { page, date, visitors}) => {
acc[page] = acc[page] || { page, dates: [], numberOfVisits: []};
acc[page].dates.push(date);
acc[page].numberOfVisits.push(visitors);
return acc;
}, {}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to find sum of all objects for some key in array of custom objects in swift

If you just want the sum of dueAmount in your duesArray with type Due then you can simply use reduce():

let totalAmount = duesArray.reduce(0.0) { $0 + ($1.dueAmount ?? 0) }

print(totalAmount) // 4500.0

Clean way to sum a object property value in a list of objects in Dart

With fold:

final total = cartItems.fold(0, (sum, item) => sum + item.amount);

EDIT: There is a long-running issue with generic methods in Dart that have a callback as a parameter where the type of the arguments cannot be inferred. This wasn't an issue in the past since the default value of a generic argument was dynamic.

However, with the release of null-safety, the type system of Dart was shaken up, and now the default type is Object?. This is a problem since you now have to ensure that the objects within the callback aren't nullable before you can add them, and the easiest way to do this is to bypass type inference and explicitly assign a generic type.

There are a few ways you can accomplish this:

// Pass generic type parameters manually
final total = cartItems.fold<int>(0, (sum, item) => sum + item.amount);

// Explicitly type parameters in the callback
final total = cartItems.fold(0, (int sum, item) => sum + item.amount);

// Explicitly type the returned value
final int total = cartItems.fold(0, (sum, item) => sum + item.amount);

Sum the nested object values in an object array

You need to supply an initial value to the reduce accumulator (previousValue which I've changed to acc), and on each iteration take the current values from the acc (or using 0 as a fallback), and add to it the item's values:





const items = [{"title":"oranges","id":5802537,"cart":{"purchased":3,"stockTotal":9},"price":3,"department":"fresh fruit and veg"},{"title":"pasta","id":5802537,"cart":{"purchased":2,"stockTotal":15},"price":1,"department":"dry goods"},{"title":"eggs","id":5802537,"cart":{"purchased":1,"stockTotal":11},"price":2,"department":"baking"}];

const val = items.reduce(function(acc, currentValue) {
return {
purchased: (acc.purchased ?? 0) + currentValue.cart.purchased,
stockTotal: (acc.stockTotal ?? 0) + currentValue.cart.stockTotal
};
}, {});

console.log(val);

Swift 3 - Reduce a collection of objects by an Int property


var total = arr.reduce(0, {$0 + $1.distance!})

The first argument is the accumulator, it is already an integer.

Note that this will crash on elements without distance. You could fix that e.g. using:

let total = arr.reduce(0, {$0 + ($1.distance ?? 0)})

or

let total = arr.compactMap { $0.distance }.reduce(0, +)

Sum of Array containing custom class (Swift)

You can use a single reduce on array.

let sumOfValues = array.reduce({$0 += ($1.value ?? 0)})


Related Topics



Leave a reply



Submit