Search code examples
javascriptformsgoogle-apps-scriptgoogle-sheetsgoogle-forms

Function to remove duplicates from Google Form


I was trying to make a script for a google spreadsheet that would remove duplicate entries that were submitted via a google form. Essentially the google form writes the entries to the google spreadsheet and I wanted any google form entry that were a duplicate to an entry already submitted through the form, to be removed automatically. This is the code that I have now:

function onFormSubmit(e) {  
 var sheet = SpreadsheetApp.openById("13ggBeSGGxhI291uPcIr0RudwxxKUigtNEN750Q2hCBM");
 var data = sheet.getDataRange().getValues();
 var newData = new Array();
 for(i in data){
   var row = data[i];
   var duplicate = false;
   for(j in newData){
     if(row.join() == newData[j].join()){
       duplicate = true;
      }
    }
    if(!duplicate){
       newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

I know parts of it are still incorrect so i was hoping someone could help me get a better idea of what I'm doing wrong so that I can make the necessary corrections. Thanks!


Solution

  • You opened a Spreadsheet object, you also need to open the actual sheet (One spreadsheets has one or more sheets).
    The sheet class has a method clearContents(), a spreadsheet doesn't.

    Try SpreadsheetApp.openById("13ggBeSGGxhI291uPcIr0RudwxxKUigtNEN750Q2hCBM").getSheetByName(whateverYourResponseSheetNameIsAsAString);.

    As for why the Spreadsheet class supports getValues() but not clearContents(), I don't know, it seems inconsistent. For the former it is implicitly running getActiveSheet().