Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  78] [ 6]  / answers: 1 / hits: 72374  / 10 Years ago, fri, june 27, 2014, 12:00:00

I have an array of objects like the following:



[
{
'name': 'P1',
'value': 150
},
{
'name': 'P1',
'value': 150
},
{
'name': 'P2',
'value': 200
},
{
'name': 'P3',
'value': 450
}
]


I need to add up all the values for objects with the same name. (Probably also other mathematical operations like calculate average.) For the example above the result would be:



[
{
'name': 'P1',
'value': 300
},
{
'name': 'P2',
'value': 200
},
{
'name': 'P3',
'value': 450
}
]

More From » arrays

 Answers
2

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);





Hope this helps.


[#70405] Wednesday, June 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skylerselenem

Total Points: 282
Total Questions: 101
Total Answers: 107

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;