Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  187] [ 7]  / answers: 1 / hits: 24286  / 11 Years ago, mon, october 7, 2013, 12:00:00

How would one take a JavaScript array of objects, such as


objArr = [
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:42},
{key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78},
{key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23},
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:54} // <- duplicate key
]

and merge duplicate keys by summing the values?


In order to get something like this:


reducedObjArr = [
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:96},
{key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78},
{key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23}
]


I have tried iterating and adding to a new array, but this didn't work:


var reducedObjArr = [];
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item = objArr[i];
key = Object.keys(item)[0];
item = item[key];

if(!result[key]) {
result[key] = item;
} else {
result[key] += item;
}
}a

More From » arrays

 Answers
24

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.


[#75168] Sunday, October 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katelinb

Total Points: 535
Total Questions: 104
Total Answers: 109

Location: Burkina Faso
Member since Sun, Jun 13, 2021
3 Years ago
;