Google AppsScript: Remove recurring (eventSeries) from Google Calendar

I have the following code that removes events from my google calendar that are flagged as Pending Removal in google sheets. The part of this code that removes single events works just fine but I need to tweak it to remove recurring events as well. Right now it only removes the first event in the recurring event series.

Note: events are indicated as pending removal in Column E or ```x[4]``. enter image description here

function calendarRemove() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheetByName('Events Calendar')
  var settingsSheet = ss.getSheetByName('Calendar Settings');
  var calendarId = 'calendarID';
  var eventCal = CalendarApp.getCalendarById(calendarId);
  var eventArray = dataSheet.getRange('A2:H').getDisplayValues();

  for (x = 0; x < eventArray.length; x++) {

    var event = eventArray[x];
    var eventName = event[1];
    var eventDate = new Date(event[0]);
    var timeZone = event[6];
    var startTime = new Date(`${event[0]} ${event[2]} ${timeZone}`);
    var endTime = new Date(`${event[0]} ${event[3]} ${timeZone}`);
    var status = event[4]; // Used in the following comparison expression

    if (status === 'Pending Removal') {
      var returnedEvents = eventCal.getEventsForDay(eventDate, {search: eventName});
      for (i = 0; i < returnedEvents.length; i++) {
        var toRemove = returnedEvents[i];
        if (toRemove.isRecurringEvent) {
          toRemove.deleteEventSeries();
        } else { toRemove.deleteEvent(); }
        eventArray[x][4] = 'Removed'; // Modifying the status value from "Pending Removal" to "Removed"
      }
    }
  }
  dataSheet.getRange('A2:H').setValues(eventArray); // Overwrite the source data with the modified array
}

Solution 1:

There's a thread that points out that issue, where you need to remove the recurrence of the event first and then delete the rest of them in the loop on Google Calendar script: remove recurrence

This script might help you out, at the end of the previous thread

function deleteEvents()
{

  var calendarName = '<Name of the Calendar>';    
  var calendar = CalendarApp.getCalendarsByName(calendarName)[0];
  var events = calendar.getEvents('<Sheet events where recurring events is set to "Yes">');

  for(var i=0; i < events.length;i++)
  {
    var ev = events[i];
    Logger.log('Checking Event Title === ' + calendar.getEventSeriesById(ev.getId()).getTitle());
    calendar.getEventSeriesById(ev.getId()).deleteEventSeries();
    Logger.log('Event Deleted');
  }
}