0

I'm wanting to remove duplicate values from the array tabData produced by the script below.

I've found numerous posts here that mention "removing duplicates from array", but don't seem to be relevant to my exact goal.

I've tried filter, I've tried using this answer and adjusting the variables to fit my script, but it did not remove the duplicates.

Surely there is a simple function that does exactly what I'm looking for, I'm just not finding it.

function getTabArray() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var version = ss.getRangeByName("version").getValue().toString();
  var updateTabsName = "updateTabs";
  var updateTabsSheet = ss.getSheetByName(updateTabsName);

  var tabDataRows = updateTabsSheet.getLastRow();
  var tabDataCols = updateTabsSheet.getMaxColumns() - 1;
  var tabDataRange = updateTabsSheet.getRange(1, 2, tabDataRows, tabDataCols);
  var tabData = tabDataRange.getValues(); // <-- REMOVE DUPLICATES

  for (var i = 0; i < tabData.length; i++) {
    if (tabData[0][i] != "" && tabData[0][i] > version) {
      for (var j = 0; j < tabData.length; j++) {
        if (tabData[j][i] != "" && j > 0) {
          Logger.log("tabData[j][i] = " + tabData[j][i]); // tabData[j][i] = all values in column
        }
      }
    }
  }
}

This is the array it currently produces:

2.20200514.2,2.20200514.0,2.20200513.2,2.20200513.1,2.20200513.0,2.20200512.0,1.20200405.1,,tabDefinitions,Sheet6,Sheet6,changeLog,Sheet6,Index,,,,Sheet7,,Sheet7,settings,,,,Sheet8,,Sheet8,tabDefinitions,,,,,,,changeLog,,,,,,,updateTabs

I want to remove all duplicates (Sheet6, Sheet7, Sheet8, etc.) from the array.

EDIT:

After one more search, I found this answer which contains exactly what was answered below, but when I use any method in that answer, I still get all duplicates. Not sure what I'm doing wrong or not doing right.

var unique = tabData.filter((v, i, a) => a.indexOf(v) === i);

EDIT 2:

I realized my array was not actually "flat", so I added var tabData = tabDataRange.getValues().flat(); and now everything works!

TC76
  • 860
  • 1
  • 8
  • 17

1 Answers1

4

You can use ES6 Set() function to remove the duplicates

const newArray = [...new Set(arrayWithDuplicates)];
Amit G.
  • 323
  • 3
  • 8