Home > Back-end >  How do I get an array of Sheets that excludes certain sheets by name, ie. these sheets but NOT those
How do I get an array of Sheets that excludes certain sheets by name, ie. these sheets but NOT those

Time:10-23

I know how to get all of the sheets from a spreadsheet. The spreadsheet will eventually get more and more sheets.

  const thisDoc = SpreadsheetApp.getActive()
  const allSheets = thisDoc.getSheets()

I have a list of string names of the two sheets in the spreadsheet that I never want to use:

 excludeList = ["template", "instructions"]

In Python I would do the following using the NOT IN keywords:

  listInclSheets = []
  for thisSheet in allSheets:
    if sheet.getName() not in excludeList:
      listInclSheets.append(thisSheet)

My Question is: How do I get a Subset of an Array excluding members based on a list of String Names of Sheets in Google Apps Script using the array.map() or array.filter() or some other cool method that is not doing it the long way?

I also know how to do it the long way using nested for loops and a boolean flag:

  const thisDoc = SpreadsheetApp.getActive()
  const arInclSheets = []
  const allSheets = thisDoc.getSheets();
  excludeList = ["template", "instructions"];
  for (thisSheet of allSheets)
  {
    var booInclude = true;
    for (anExcludeName of excludeList)
    {
      Logger.log("is "  thisSheet.getName()   "equal to "   anExcludeName  "?");
      if (thisSheet.getName() == anExcludeName);
      {
        booInclude = false; 
      }
    }
    if ( booInclude)
    {
      arInclSheets.push(thisSheet);
    }
  }
  Logger.log(arInclSheets);
  for (thisSheet of arInclSheets)
  {
    Logger.log(thisSheet.getName());
  }
}

P.S. map functions with fancy one line coding always confuse me, so please explain them so I can get unconfused by them.

CodePudding user response:

Create a exclusion Set and filter the sheets by it's name:

const excludeSet = new Set(["template", "instructions"]);
const includedSheets = allSheets.filter(sheet => !excludeSet.has(sheet.getName()))
  • Related