user11899141
user11899141

Reputation:

Google Apps Script (Spreadsheet) - selecting an array in spreadsheet based on a condition in cells

I am trying to select an array from google sheets to create google calendar events based on that. The code chunk below runs just fine and gets the job done. But I want to be able to only select the range that has value of "select" in their column D. I know it is probably a very easy answer but I am new to JS.

function calendarSync() {
    var spreadSheet = SpreadsheetApp.getActiveSheet;
    var eventCal = CalendarApp.getCalendarById(calendarId);
// Below instead of selecting the entire range I only need the rows that have a value of "select" in their D cell.
    var eventArray = spreadSheet.getRange("A1:D100").getValues();
    
    for (x=0; x<eventMatrix.length; x++){
      var calEvent = eventArray[x];
      var eventName = calEvent[0]
      var startTime = calEvent[1];
      var endTime = calEvent[2];
      
      eventCal.createEvent(eventName, startTime, endTime);
    }

Upvotes: 0

Views: 428

Answers (1)

Tanaike
Tanaike

Reputation: 201723

In your situation, how about the following modification?

From:

    var spreadSheet = SpreadsheetApp.getActiveSheet;
    var eventCal = CalendarApp.getCalendarById(calendarId);
// Below instead of selecting the entire range I only need the rows that have a value of "select" in their D cell.
    var eventArray = spreadSheet.getRange("A1:D100").getValues();

To:

var spreadSheet = SpreadsheetApp.getActiveSheet(); // Please add ()
var eventCal = CalendarApp.getCalendarById(calendarId);
var eventArray = spreadSheet.getRange("A1:D100").getValues().filter(r => r[3] == "select");
  • By this modification, eventArray has the values that select is included in the column "D".

Reference:

Upvotes: 1

Related Questions