I have a list of times slots here eg:
const times = [
{ start: '2020-07-09T08:00:00.000+02:00', end: '2020-07-09T09:30:00.000+02:00' },
{ start: '2020-07-09T08:30:00.000+02:00', end: '2020-07-09T10:00:00.000+02:00' },
]
While I'm trying to sort them by day using momentjs and lodash to get something like:
{
{startTime: '08:00', endTime: '08:30'}
{startTime: '08:30', endTime: '09:00'}
{startTime: '08:00', endTime: '08:30'}
{startTime: '08:30', endTime: '09:00'}
}
and I ended up with this solution for now:
const groupedAndFormatted = groupBy(times, date => moment(date.start_time).startOf('day').format('MMM Do YY'))
But this one didn't really give me the correct solution, any ideas?
First you need to sort them into the correct order, we will do this with sort and unix time stamps.
Then group them with the dddd
const times = [
{ start_time: '2020-07-09T08:00:00.000+02:00', endTime: '2020-07-09T09:30:00.000+02:00' },
{ start_time: '2020-07-09T08:30:00.000+02:00', endTime: '2020-07-09T10:00:00.000+02:00' },
{ start_time: '2020-07-07T09:00:00.000+02:00', endTime: '2020-07-07T10:30:00.000+02:00' }
];
const sorted_times = times.sort((a,b) => moment(a.start_time).unix() - moment(b.start_time).unix())
const grouped = _.groupBy(sorted_times, date => moment(date.start_time).format("dddd"))
const formatted = _.mapValues(grouped, dates => {
return dates.map(times => {
return {
start_time: moment(times.start_time).format("hh:mma"),
endTime: moment(times.endTime).format("hh:mma"),
}
})
})
However this will not work if you end up having multiple tuesdays on different dates.