Search code examples
google-apps-scriptgoogle-sheetsgoogle-apps

Google Apps Script - How to Update Code That Creates Tabs in Google Sheets File


I currently have code that takes subsets from a raw dataset based on a column and pastes each subset into separate tabs. The unique value from the column that we filtered on becomes the tab name.

Is there anyway to update the code to take the unique value + hardcode "check" in the tab name? So essentially, right now, if I have a raw dataset and I filter on column D. That column has 2 categories (Toys and Food). The code will create 2 tabs in the file and the first tab name would be 'Toys' and the 2nd tab name would be 'Food'. I want to change that to be 'Toys Check' and 'Food Check' instead.

Below is the code that is being utilized to turn the subsets of a raw dataset into separate tabs in the same Google Sheets File:

function getSubsetDataComplaintsDynamic() {
  const shName = "RawData";
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [headers, ...values] = ss.getSheetByName(shName).getDataRange().getValues()
  const list = values.map(r => r[3]).flat().filter(onlyUnique).sort()
  
  list.forEach(elem => {
    try {
      if (elem != '') {
        const result = [headers, ...values.filter(r => r[3].includes(elem))]
        const sheet = ss.insertSheet(elem);
        sheet.getRange(1, 1, result.length, result[0].length).setValues(result);
      }
    } catch (e) {
      Browser.msgBox(e)
    }
  })
}

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

Solution

  • Try this change: const sheet = ss.insertSheet(elem + " Check") inside the if statement