So I have an existing array with three objects:
[ { date: 3/12/2022, oService: 10}
{ date: 3/13/2022, oService: 12, aService: 1}
{ date: 3/13/2022, oService: 1 }]
Based on the date, I would like to get something that looks like the following:
[ {date: 3/12/2022, oService: 10}
{date: 3/13/2022, oService: 13, aService: 1}]
additionally, I could have up to 10 services, so I cant reduce by prev.oService. I'll have an array of services that looks something like:
const Services = [aService, bService, cService, oService, yService]
I think it's best to think of the problem as 2 different steps:
groupBy that you should be able to look up on StackOverflow or borrow from an existing library.The merge operation is a bit more custom than the groupBy operation. You can implement it in many ways. I would propose to:
merge to deal with just 2 objectsmerge, loop over all unique keys in those objects and sum them (excluding the date key)merge to a date group, use reduce. Note that it's safe to not provide a seed argument here, because you are guaranteed to not have empty groups.// Merge two date-service entries in to one
const merge = (a, b) => {
const merged = Object.assign({}, a);
Object.keys(b).forEach(k => {
if (k !== "date")
merged[k] = (merged[k] || 0) + b[k];
});
return merged;
};
const input = [ { date: "3/12/2022", oService: 10},
{ date: "3/13/2022", oService: 12, aService: 1},
{ date: "3/13/2022", oService: 1 }];
// Create groups that have a matching date
const byDate = groupByProp("date", input);
// Reduce each group to a single item by merging
const all = Object.values(byDate).map(xs => xs.reduce(merge));
console.log(all);
// A basic `groupBy` implementation
function groupByProp(prop, xs) {
return xs.reduce(
(groups, x) => {
const k = x[prop];
if (!groups[k]) groups[k] = [x];
else groups[k].push(x);
return groups;
},
{}
);
}