Sort calendar by start date

Hi,
I have the following lines of code to read appointments from the calendar.
This also works very well.

However, the sorting is not always correct.
Could it be that it is sorted by the end date?

This is how the following two dates are listed. But it would be more correct if they are sorted by the start time. How to do it?
11.01.2021 14:00 o’clock - 15:00 o’clock
11.01.2021 12:00 o’clock - 16:00 o’clock

Thanks

  const date = new Date();

  let events = [];
  if (showEventsOnlyForToday) {
    events = await CalendarEvent.today([]);
  } else {
    let dateLimit = new Date();
    dateLimit.setDate(dateLimit.getDate() + 9999);
    events = await CalendarEvent.between(date, dateLimit);
  }
  
  const futureEvents = [];
  // if we show events for the whole week, then we need to filter allDay events
  // to not show past allDay events
  // if allDayEvent's start date is later than a day ago from now then show it
  for (const event of events) {
    if (
      (showAllDayEvents &&
        event.isAllDay &&
        event.startDate.getTime() >
          new Date(new Date().setDate(new Date().getDate() - 1))) ||
      (event.endDate.getTime() > date.getTime() &&
        !event.title.startsWith("Canceled:")
    )
    ) {
      futureEvents.push(event);
    }
  }


// if we have events today; else if we don't
  if (futureEvents.length !== 0) {
    // show the next 3 events at most
    const numEvents = futureEvents.length
    for (let i = 0; i < numEvents; i += 1) {      
      event_tmp = futureEvents[i]
      console.log("Begin: " + event_tmp.startDate)
      console.log("End: " + event_tmp.endDate)
      console.log(" ")
    }
  }

For myself it is not sorting by endDate, I was not able to reproduce your bad sorting.

But to make sure it is always sorted by startDate you could add

futureEvents.sort(function rankDate(a, b) {
   var dateA = a.startDate
   var dateB = b.startDate
   return dateA - dateB
})

source

I tried sorting by endDate with success.

Thanks. It works well.