I have looked through stack overflow and feel like there is a much easier solution using map and reduce to solve this problem but this is my clumsy way to solve it so far. I need to sum up data by dates without having a "key" in the original json object. See below for the code snippet and result that seems to work. I would appreciate any input on doing this better. Thank you.
// input
var array1 = [{'2019-07-13': 1, '2019-07-14': 4, '2019-07-15': 7}];
var array2 = [{'2019-07-13': 5, '2019-07-14': 8, '2019-07-15': 6}];
var array3 = [{'2019-07-13': 2, '2019-07-14': 1, '2019-07-15': 9}];
// output should look like this
// [{2019-07-13: 8, 2019-07-14: 13, 2019-07-15: 22}]
var combinedArray = [];
var finalArraySum = [];
// combine all the arrays into one...
var arrays = array1.concat(array2, array3);
arrays.forEach((array, index) => {
Object.keys(array).forEach(function(key) {
var element = [key, array[key]];
combinedArray.push(element);
})
});
// loop through the combined arrays
combinedArray.forEach((item, index) => {
// figure out if the item already exists in the final summed up array
var sumExists = finalArraySum.filter((innerItem, index) => {
return innerItem[0] === item[0];
});
// if not exists, then push the initial one
if(sumExists.length === 0) {
finalArraySum.push([item[0], item[1]]);
} else {
// else add up to the already existing one
sumExists[0][1] = item[1] + sumExists[0][1];
}
})
console.log(finalArraySum);
var finalObject = [];
var stringObject = '{';
finalArraySum.forEach((item, index) => {
console.log(item);
stringObject = stringObject + '"' + item[0] + '":"' + item[1] + '",';
});
stringObject = stringObject.substr(0, stringObject.length - 1) + "}";
console.log(JSON.parse(stringObject));
finalObject.push(JSON.parse(stringObject));
console.log(finalObject);