Sum JavaScript Object Propertya Values With the Same Object Propertyb in an Array of Objects

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/

Sum JavaScript object propertyA values with the same object propertyB in an array of objects

You should be assigning each object not found to the result with its .key property.

If it is found, then you need to add its .val.

var temp = {};
var obj = null;
for(var i=0; i < objArr.length; i++) {
obj=objArr[i];

if(!temp[obj.key]) {
temp[obj.key] = obj;
} else {
temp[obj.key].val += obj.val;
}
}
var result = [];
for (var prop in temp)
result.push(temp[prop]);

Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.

How to sum values with the same key In an array of objects?

Array#reduce is one way of getting there. Basically we just check each iteration for a match on the category. If there is match, we add the appropriate values together (converting both to numbers on the fly)

let arrayOfObjects = [{
"grouppresentation": "11",
"evaluation": null,
"datacontext": null,
"category": "Group Presentation"
},
{
"grouppresentation": null,
"evaluation": "23",
"datacontext": null,
"category": "Evaluation"
},
{
"grouppresentation": null,
"evaluation": "46",
"datacontext": null,
"category": "Evaluation"
},
{
"grouppresentation": "44",
"evaluation": null,
"datacontext": null,
"category": "Group Presentation"
},
{
"grouppresentation": null,
"evaluation": null,
"datacontext": "21",
"category": "Data Context"
}
]

let newArrayOfObjects = arrayOfObjects.reduce((b, a) => {
let ind = b.findIndex(e => e.category === a.category);
let c = a.category.toLowerCase().split(' ').join('');
if (ind > -1) {
b[ind][c] = +b[ind][c] + +a[c]
} else {
a[c] = +a[c] || 0
b.push(a)
}
return b;
}, []);

console.log(newArrayOfObjects)

Sum similar keys in an array of objects

First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'. Once you build this object, iterate through the properties and push them to another array.

Here is some code:

var obj = [

{ 'name': 'P1', 'value': 150 },

{ 'name': 'P1', 'value': 150 },

{ 'name': 'P2', 'value': 200 },

{ 'name': 'P3', 'value': 450 }

];

var holder = {};

obj.forEach(function(d) {

if (holder.hasOwnProperty(d.name)) {

holder[d.name] = holder[d.name] + d.value;

} else {

holder[d.name] = d.value;

}

});

var obj2 = [];

for (var prop in holder) {

obj2.push({ name: prop, value: holder[prop] });

}

console.log(obj2);

How to sum the array of object values and assigned them to the relevant key name

solved using reduce and forEach

Inside the reduce function I'm running a forEach on the array of keys of the incomes object/attribute. For each key which is a date I'm checking if the accumulator of the reduce function contains an attribute for each date and creates if not. After creating the attribute I'm summing the value for the current date attribute.

const data = [{
group: 'A',
incomes: {
"2019-12": 100,
"2020-12": 200,
"2021-12": 15
}
},
{
group: 'B',
incomes: {
"2019-12": 25,
"2020-12": 50,
}
}
]

const totalIncomes = data.reduce((acc, curr) => {
Object.keys(curr.incomes).forEach((key, index) => {
if (!acc[key]) {
acc[key] = 0
}
acc[key] += curr.incomes[key]
})
return acc
}, {})

console.log(totalIncomes)

How to sum up values of same field in array of objects?

You can use reduce() to do that.

Iterate on given data and if an item with same category as current item exists, then add the amount, else add current item as a new entry.

const data = [

{ category: 'shopping', amount: 50 },

{ category: 'rent', amount: 1000 },

{ category: 'groceries', amount: 20 },

{ category: 'shopping', amount: 50 }

];

let result = data.reduce((acc, curr) => {

let item = acc.find(item => item.category === curr.category);

if (item) {

item.amount += curr.amount;

} else {

acc.push(curr);

}

return acc;

}, []);

console.log(result);

How to sum properties of elements in an object-array?

The below may be one possible solution to achieve the desired objective.

Code Snippet

// a small helper method to convert key by leaving out the z-s in: '/xxxx?zzz'
const convertKey = x => (x.split('?')[0]);

// use reduce to iterate thru the array & obtain a result-object
// destructure to get 'x', 'y'
// if 'x' already present, add 'y'
// else create an object with 'x', 'y' props
// return the `Object.values` of the result-object
const transform = arr => (
Object.values(
arr.reduce(
(acc, {x, y}) => ({
...acc,
[convertKey(x)]: {
...(acc[convertKey(x)] || {x}),
y: (acc[convertKey(x)]?.y || 0) + y
}
}),
{}
)
)
);

const data = [
{
"x": "/shop.html",
"y": 3
},
{
"x": "/",
"y": 2
},
{
"x": "/?test324",
"y": 1
},
{
"x": "/account.html",
"y": 1
},
{
"x": "/account.html?test1",
"y": 1
},
{
"x": "/shop.html?test543",
"y": 1
}
];

console.log(transform(data));

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)


Related Topics



Leave a reply



Submit