I have an array of appointments objects:
let appointments = [
{ _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
{ _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"},
{ _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"},
{ _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"},
{ _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
]
my goal is to create a new array based on the days of the appointments and place them inside, like so:
{ days:
{ 2022-01-20: [
{ _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
{ _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"}
]},
{ 2022-01-21: [
{ _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"}
]},
{ 2022-01-22: [
{ _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"}
]},
{ 2022-01-23: []},
{ 2022-01-24: []},
{ 2022-01-25: [
{ _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
]},
}
The first 10 characters of 'date' could become the new values (excluding duplicates) and inside them there should be the proper appointments, as they are in the source - only organized by the days.
Another feature that I'm trying to make is inserting empty days between the active days (example in the second code)
Thanks for your help
const appointments = [
{ _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
{ _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"},
{ _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"},
{ _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"},
{ _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
];
const appointmentsByDate = appointments.reduce(
(acc, appointment) => {
// split the date string and store index 0 as date variable.
const [date] = appointment.date.split('T');
return {
...acc,
// overwrite or add date key to the accumulator.
// if the date key already exists, spread the existing value into the new value
[date]: [...(acc[date] || []), appointment],
};
},
{} // starting accumulator (acc) value
);
console.log(appointmentsByDate);