How would one take a javascript array of objects such as:
my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-04
Simpler reduce than posted elsewhere
const 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}];
const output = objArr.reduce((accumulator, cur) => {
let date = cur.key;
let found = accumulator.find(elem => elem.key === date)
if (found) found.val += cur.val;
else accumulator.push(cur);
return accumulator;
}, []);
console.log(output)
you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js
var 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}
];
var aggregatedObject = Enumerable.From(objArr)
.GroupBy("$.key", null,
function (key, g) {
return {
key: key,
contributions: g.Sum("$.val")
}
})
.ToArray();
console.log(aggregatedObject);
<script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
which is pretty easy as compare to looping. i hope this may help.
var targetObj = {};
for (var i = 0; i < objArr.length; i++) {
if (!targetObj.hasOwnProperty(objArr[i].key)) {
targetObj[objArr[i].key] = 0;
}
targetObj[objArr[i].key] += objArr[i].val;
}
http://jsfiddle.net/HUMxp/