I have a query that is getting values for the last 7 days for a user. These entries may be (2) or they may be (20) what's important is the values for each date are calculated and added.
here is the data:
[ { calories: '1170.00', upload_date: 2019-12-31T21:41:42.943Z },
{ calories: '2188.00', upload_date: 2019-12-31T21:41:56.604Z },
{ calories: '1079.00', upload_date: 2019-12-31T21:43:06.372Z },
{ calories: '2188.00', upload_date: 2019-12-31T21:42:56.577Z },
{ calories: '445.00', upload_date: 2019-12-31T21:42:45.559Z },
{ calories: '1170.00', upload_date: 2019-12-31T21:42:28.609Z },
{ calories: '445.00', upload_date: 2019-12-31T21:42:15.793Z },
{ calories: '1079.00', upload_date: 2019-12-31T21:42:05.049Z } ]
Now in this example the upload dates are the same, that's fine but what it should return is {calories:sum of all, upload_date:"2019-12-31"} if there were seven days here I would need this to be a total of seven entries.
What I have tried:
I have tried several variations of using Date object and some array filtering but i did not arrive at a result I was content with and wanted to get a better way of doing it from here.
there needs to be a loop, a comparison of the date object(s) of all the keys in the objects and if they're equal add (+=) to the sum value of that particular day; then continue if there are more entries and repeat until all objects values have been added taking into respect the dates.
const input = [ { calories: '1170.00', upload_date: '2019-12-31T21:41:42.943Z' },
{ calories: '2188.00', upload_date: '2019-12-31T21:41:56.604Z' },
{ calories: '1079.00', upload_date: '2019-12-31T21:43:06.372Z' },
{ calories: '2188.00', upload_date: '2019-12-31T21:42:56.577Z' },
{ calories: '445.00', upload_date: '2019-12-31T21:42:45.559Z' },
{ calories: '1170.00', upload_date: '2019-12-31T21:42:28.609Z' },
{ calories: '445.00', upload_date: '2019-12-31T21:42:15.793Z' },
{ calories: '1079.00', upload_date: '2019-12-31T21:42:05.049Z' },
{ calories: '1079.00', upload_date: '2019-12-30T21:42:05.049Z' } // added for demo
]
const output = input.reduce((all, next) => {
const s = new Date(next.upload_date)
const key = `${s.getFullYear()}-${(s.getUTCMonth() + 1)}-${s.getUTCDate()}`
const exist = all.find(v => v.upload_date === key)
if (exist) {
exist.calories += Number(next.calories)
} else {
all.push({
calories: Number(next.calories),
upload_date: key
})
}
return all
}, [])
console.log(output)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments