I'm looking to reduce an array of objects by matching identical date strings and add the totals together of those matching dates and combine them into a single object. I could have an array several thousand items long so I'm trying to increase (where ever possible) and complexity.
// before
let objArr = [
{
date: '01/01/2018',
total: 1
},
{
date: '01/01/2018',
total: 2
},
{
date: '01/02/2018',
total: 3
},
{
date: '01/02/2018',
total: 4
},
...
]
// final result
let finalArr = [
{
date: '01/01/2018',
total: 3
},
{
date: '01/02/2018',
total: 7
},
...
]
I couldn't seem to get the hang of reducing them using reduce:
objArr.reduce((acc, obj) => {
acc.set(obj.date, (acc.get([obj.date]) || 0) + obj.total);
return acc;
}, new Map())
The result always ends up with the wrong totals or the last several array objects look like:
// bad output
badArray = [
...,
{
date: '01/02/2018',
total: 4
},
{
date: undefined,
total: NaN
},
{
date: undefined,
total: NaN
}
]
I wrote a script to check to ensure all the values in the date and total properties existed the way they needed to but I still end up with a bad array. The assumption here is my reduce function isn't right.