Skip to content

How to add the values ​in an array of objects depending on the date value of each object

I have this array:

[{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}]

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:

 [{month: 12 ,total distance: 2000, total time: 4900}, 
  {month: 02 , total distance: 1500, total time: 6400} ]

Answer

you can use reduce to group them by month which will give an object like

{
  12: {
    distance: 2000,
    month: 12,
    time: 4900
  },
  2: {
    distance: 1500,
    month: 2,
    time: 6400
  }
}

and using Object.values get the values array of it

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}]

let res = Object.values(x.reduce((acc,{start_date,distance,time})=> {
    let month = new Date(start_date).getMonth()+1
  if(!acc[month])acc[month] = {totalDistance:0,totalTime:0,month:month}
  acc[month].totalDistance+=distance
  acc[month].totalTime+=time
  return acc;
},{}))


console.log(res)