Lets say i have an array of objects which features a start and end date:
var events = [
{start: '2021-01-25 10:00:00', end: '2021-01-25 11:00:00', title: 'Event #1'},
{start: '2021-01-25 10:00:00', end: '2021-01-25 12:00:00', title: 'Event #2'},
{start: '2021-01-25 18:00:00', end: '2021-01-25 19:00:00', title: 'Event #3'},
{start: '2021-01-25 19:00:00', end: '2021-01-25 20:00:00', title: 'Event #4'},
{start: '2021-01-25 19:30:00', end: '2021-01-25 20:30:00', title: 'Event #5'},
{start: '2021-01-25 23:00:00', end: '2021-01-25 23:30:00', title: 'Event #6'},
]
As you can see, the time ranges might partially overlap between records. The dates are Date
objects.
I want to group these records into smaller groups, where each group is at least X hours apart. Lets say the gap is 5 hours, in that case my expected result would be this:
var event_groups = [
[
{start: '2021-01-25 10:00:00', end: '2021-01-25 11:00:00', title: 'Event #1'},
{start: '2021-01-25 10:00:00', end: '2021-01-25 12:00:00', title: 'Event #2'},
],
[
{start: '2021-01-25 18:00:00', end: '2021-01-25 19:00:00', title: 'Event #3'},
{start: '2021-01-25 19:00:00', end: '2021-01-25 20:00:00', title: 'Event #4'},
{start: '2021-01-25 19:30:00', end: '2021-01-25 20:30:00', title: 'Event #5'},
{start: '2021-01-25 23:00:00', end: '2021-01-25 23:30:00', title: 'Event #6'},
]
]
If the gap is 2 hours, the results would change like this:
var event_groups = [
[
{start: '2021-01-25 10:00:00', end: '2021-01-25 11:00:00', title: 'Event #1'},
{start: '2021-01-25 10:00:00', end: '2021-01-25 12:00:00', title: 'Event #2'},
],
[
{start: '2021-01-25 18:00:00', end: '2021-01-25 19:00:00', title: 'Event #3'},
{start: '2021-01-25 19:00:00', end: '2021-01-25 20:00:00', title: 'Event #4'},
{start: '2021-01-25 19:30:00', end: '2021-01-25 20:30:00', title: 'Event #5'},
],
[
{start: '2021-01-25 23:00:00', end: '2021-01-25 23:30:00', title: 'Event #6'},
]
]
As for where i'm standing so far with my code(its not much...)
var event_groups = [];
var event_group = [];
events.forEach(function(event){
//If its an empty group, just add the data and move forward
if(!event_group.length) {
event_group.push(event);
continue;
}
})
Any ideas how should i solve this problem?
question from:
https://stackoverflow.com/questions/65903806/how-can-i-group-an-array-of-date-ranges-into-smaller-groups-with-a-minimum-time