I have this array:
JavaScript
x
4
1
[{start_date: "2022-12-05T04:00:00Z" ,distance: 1000, time: 3600}
2
,{start_date: "2022-02-07T04:00:00Z" ,distance: 1500, time: 6400},
3
{start_date: "2022-12-08T04:00:00Z" ,distance: 1000, time: 1300}]
4
I want to add the distance and time values grouping them by the month indicated by the start_date value. For example, if two start_dates have the same month 2022-12-01 and 2022-12-08, how can I add the distance and time values of those two months?
so i get a new array like this:
JavaScript
1
3
1
[{month: 12 ,total distance: 2000, total time: 4900},
2
{month: 02 , total distance: 1500, total time: 6400} ]
3
Advertisement
Answer
you can use reduce
to group them by month which will give an object like
JavaScript
1
13
13
1
{
2
12: {
3
distance: 2000,
4
month: 12,
5
time: 4900
6
},
7
2: {
8
distance: 1500,
9
month: 2,
10
time: 6400
11
}
12
}
13
and using Object.values
get the values array of it
JavaScript
1
12
12
1
let x = [{start_date: "2022-12-05T04:00:00Z" ,distance: 1000, time: 3600},{start_date: "2022-02-07T04:00:00Z" ,distance: 1500, time: 6400},{start_date: "2022-12-08T04:00:00Z" ,distance: 1000, time: 1300}]
2
3
let res = Object.values(x.reduce((acc,{start_date,distance,time})=> {
4
let month = new Date(start_date).getMonth()+1
5
if(!acc[month])acc[month] = {totalDistance:0,totalTime:0,month:month}
6
acc[month].totalDistance+=distance
7
acc[month].totalTime+=time
8
return acc;
9
},{}))
10
11
12
console.log(res)