I see many posts/questions addressing this issue, so I assume it is not trivial. I am quite a beginner, looking for a more elegant solution.
I need to reduce this kind of array containing 1-minute detailed data into 5-minute data. Just computing the sum of consecutive values for 5 minutes, and then recreating a shorter array. Then the timestamp "created_at" should be the timepoint of the end of the 5-minute period.
let array = [
{ steps: 40, created_at: '2022-09-03T11:36:00.000Z' },
{ steps: 13, created_at: '2022-09-03T11:37:00.000Z' },
{ steps: 40, created_at: '2022-09-03T11:38:00.000Z' },
{ steps: 40, created_at: '2022-09-03T11:39:00.000Z' },
{ steps: 34, created_at: '2022-09-03T11:40:00.000Z' },
{ steps: 86, created_at: '2022-09-03T11:41:00.000Z' },
{ steps: 23, created_at: '2022-09-03T11:42:00.000Z' },
{ steps: 78, created_at: '2022-09-03T11:43:00.000Z' },
{ steps: 67, created_at: '2022-09-03T11:44:00.000Z' },
{ steps: 80, created_at: '2022-09-03T11:45:00.000Z' },
{ steps: 34, created_at: '2022-09-03T11:46:00.000Z' },
{ steps: 64, created_at: '2022-09-03T11:47:00.000Z' },
{ steps: 32, created_at: '2022-09-03T11:48:00.000Z' },
{ steps: 78, created_at: '2022-09-03T11:49:00.000Z' },
{ steps: 45, created_at: '2022-09-03T11:50:00.000Z' }
]
My solution is too complex I think:
const moment = require(`moment`);
const newArray = array.map(
(item)=> {
const timestamp = moment(item.created_at).valueOf();
const timeStampgroup = Math.ceil((timestamp)/300000);
return {...item, timeStampgroup: timeStampgroup}
}
);
//console.log(newArray);
const reducedArray = Array.from(newArray.reduce(
(m, {timeStampgroup: timeStampgroup, steps}) => m.set(timeStampgroup, (m.get(timeStampgroup) || 0) + steps), new Map
), ([timeStampgroup, steps]) => ({timeStampgroup, steps}));
//console.log(reducedArray);
const result = reducedArray.map(entry => ({steps : entry.steps, created_at : moment(entry.timeStampgroup*300000).toISOString()}));
console.log(result);
[
{ steps: 167, created_at: '2022-09-03T11:40:00.000Z' },
{ steps: 334, created_at: '2022-09-03T11:45:00.000Z' },
{ steps: 253, created_at: '2022-09-03T11:50:00.000Z' }
]
Does anyone see a less complicated way to achieve the same result, in one pass maybe ?
Thanks a lot !
Lorenzo
created_at
something like2022-09-03T11:53:00.000Z
. In other words, where should thesteps
for minutes 51, 52, 53 be displayed?in one pass maybe ?
--> Assume this means with just one loop. Yes, it is possible with just one loop (one such solution using.reduce()
has been posted below) – Joanjoana