I have the following array of objects:
const dataSet = [
{
createdOn: '2020-06-01',
id: 1,
value: 12
},
{
createdOn: '2020-06-01',
id: 2,
value: 23
},
{
createdOn: '2020-06-02',
id: 3,
value: 40
},
{
createdOn: '2020-06-03',
id: 4,
value: 15
}
]
What I'd like to be able to return is the follow:
[
{
createdOn: '2020-06-01',
value: 35 // sum of 12 + 23
},
{
createdOn: '2020-06-02',
value: 75 // sum of 35 + 40
},
{
createdOn: '2020-06-03',
value: 90 // sum of 75 + 15
}
]
So the outcome I'm after is:
- When there are two (or more) objects with the same
createdOn
date, then theirvalue
s should be added together in a single object for thatcreatedOn
key. - Each object's
value
also then needs to be added together, creating an accumulatedvalue
from the previous object.
After a bit of searching through SO I found some code which helps me achieve the first point:
dataSet.reduce((acc, cur) => {
const date = cur.createdOn
const found = acc.find(elem => elem.createdOn === date)
if (found) {
found.value += cur.value
} else {
acc.push(cur)
}
return acc
}, [])
I just can't figure out how to achieve the accumulated value part.
Thanks in advance, and have a great weekend.