'Create Filter View in Google Sheet App Scripts [closed]

I have a list of items in column A in a Google Sheet.

I want to create an App Script that will create a Filter View (different than a filter) for each unique value in Column A. I know I need to use addFilterView, but I'm having trouble getting the script written correctly.

Filter
A
A
A
B
C
C
D


Solution 1:[1]

Try

function create_filter_view() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var sheet = ss.getSheetByName("Sheet1");
  var sheetId = sheet.getSheetId();
  var range = sheet.getRange("A2:A" + sheet.getLastRow());
  var values = range.getValues();
  uniqueValues = values.flat().filter(onlyUnique)
  var requests = uniqueValues.map((a) => ({ addFilterView: { filter: { title: a, range: { sheetId: sheetId, startRowIndex: 0, startColumnIndex: 0 }, filterSpecs: [{ columnIndex: 0, filterCriteria: { condition: { type: "TEXT_EQ", values: [{ userEnteredValue: a }] } } }] } } }));
  var response = Sheets.Spreadsheets.batchUpdate({ requests }, ssId);
}
function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

enable google sheets api

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Steelson