Better Way to Sum a Property Value in an Array

Better way to sum a property value in an array

Updated Answer

Due to all the downsides of adding a function to the Array prototype, I am updating this answer to provide an alternative that keeps the syntax similar to the syntax originally requested in the question.

class TravellerCollection extends Array {
sum(key) {
return this.reduce((a, b) => a + (b[key] || 0), 0);
}
}
const traveler = new TravellerCollection(...[
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
]);

console.log(traveler.sum('Amount')); //~> 235

Original Answer

Since it is an array you could add a function to the Array prototype.

traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
];

Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][prop]
}
return total
}

console.log(traveler.sum("Amount"))

The Fiddle: http://jsfiddle.net/9BAmj/

How can I find the sum of of Similar array object values and separate them based on their values

Just group by the desired property using reduce method.

var data = [{ count: 2, created_data: "2022 07 19" },
{ count: 4, created_data: "2022 07 19" },
{ count: 4, created_data: "2022 07 19" },
{ count: 1, created_data: "2022 07 20" },
{ count: 1, created_data: "2022 07 20" }]

var result = [data.reduce(function(agg, item) {
agg[item.created_data] = (agg[item.created_data] || 0) + item.count
return agg
}, {})]

console.log(result)

How to calculate the sum of numbers in deeply nested array of objects using JavaScript?

Your data structure looks pretty simple, so I'll just explain in plain english how to accomplish it:

The simple straight forward way is to ignore all the fancy functional things you can do on arrays, and just do this:

Set a sum variable equal to 0. Iterate over every element of initialData. On each element, iterate over every element of data. On each data element, iterate over every element of variations. Add the price property to your sum variable.

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.

How to sum values in an array of objects in javascript

The following function can be used. I have used ES6. The function takes inputs which will be your input object.

const sumIt = (inputs) => {

const result = {};

inputs.forEach((input) => {

const key = `${input.Daypart}_${input.day_of_week}`;

if (key in result) {

result[key].uplift = result[key].uplift + input.uplift;

} else {

result[key] = { ...input };

}

});

return result;

};


Related Topics



Leave a reply



Submit