0

I have date range like this and I want to create array based on each month.

1 => Thu Feb 16 2023
1 => Fri Feb 17 2023
1 => Sat Feb 18 2023
1 => Sun Feb 19 2023
1 => Mon Feb 20 2023
1 => Tue Feb 21 2023
1 => Wed Feb 22 2023
1 => Thu Feb 23 2023
1 => Fri Feb 24 2023
1 => Sat Feb 25 2023
1 => Sun Feb 26 2023
1 => Mon Feb 27 2023
1 => Tue Feb 28 2023
2 => Wed Mar 01 2023
2 => Thu Mar 02 2023
2 => Fri Mar 03 2023

I need array like

1 => [Fri Feb 17 2023, Sat Feb 18 2023, ...],
2 => [Wed Mar 01 2023, Thu Mar 02 2023, ...]

And this is my code

let dts = {};
newDates.forEach((dt, i) => {
  let mn = new Date(dt).getMonth();
  dts[mn] = dt;
});
console.log(dts);

I got result like this

1 : Tue Feb 28 2023
2 : Fri Mar 03 2023

Got last element only. How to solve this? Thanks

PNG
  • 287
  • 2
  • 6
  • 18

1 Answers1

1

You have the right basic idea. You need to create an array and push the value to it.

Your way with forEach

const dts = {};
newDates.forEach((dt, i) => {
  const mn = new Date(dt).getMonth();
  dts[mn] = dts[mn] || [];
  dts[mn].push(dt);
});

Using reduce

const dts = newDates.reduce((acc, dt) => {
  const mn = new Date(dt).getMonth();
  acc[mn] = acc[mn] || [];
  acc[mn].push(dt);
  return acc;
}, {});
epascarello
  • 204,599
  • 20
  • 195
  • 236