Skip to content
Advertisement

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

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement