How would one take a JavaScript array of objects, such as
JavaScript
x
7
1
objArr = [
2
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:42},
3
{key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78},
4
{key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23},
5
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:54} // <- duplicate key
6
]
7
and merge duplicate keys by summing the values?
In order to get something like this:
JavaScript
1
7
1
reducedObjArr = [
2
{key:"Mon Sep 23 2013 00:00:00 GMT-0400", val:96},
3
{key:"Mon Sep 24 2013 00:00:00 GMT-0400", val:78},
4
{key:"Mon Sep 25 2013 00:00:00 GMT-0400", val:23}
5
]
6
7
I have tried iterating and adding to a new array, but this didn’t work:
JavaScript
1
14
14
1
var reducedObjArr = [];
2
var item = null, key = null;
3
for(var i=0; i<objArr.length; i++) {
4
item = objArr[i];
5
key = Object.keys(item)[0];
6
item = item[key];
7
8
if(!result[key]) {
9
result[key] = item;
10
} else {
11
result[key] += item;
12
}
13
}a
14
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
.
JavaScript
1
15
15
1
var temp = {};
2
var obj = null;
3
for(var i=0; i < objArr.length; i++) {
4
obj=objArr[i];
5
6
if(!temp[obj.key]) {
7
temp[obj.key] = obj;
8
} else {
9
temp[obj.key].val += obj.val;
10
}
11
}
12
var result = [];
13
for (var prop in temp)
14
result.push(temp[prop]);
15
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.