Home > front end >  Remove duplicate rows based on a column
Remove duplicate rows based on a column

Time:09-22

I have this function that check duplicate rows data on a sheet, and remove it. But i need it to check only the first column and use it to remove the entire row. What i have to change?

function removerDuplicata() {
var sheet = SpreadsheetApp.getActiveSheet();
var intervalo = sheet.getRange("A2:H")
var data = intervalo.getValues();
var novaData = new Array();
for(i in data){
var row = data[i];
var duplicata = false;
for(j in novaData){
  if(row.join() == novaData[j].join()){
    duplicata = true;
  }
}
if(!duplicata){
  novaData.push(row);
}
}
 intervalo.clearContent();
  sheet.getRange(2, 1, novaData.length, 
  novaData[0].length).setValues(novaData);
}

CodePudding user response:

Remove Duplicates on Column A

function removerDuplicata() {
  var sh = SpreadsheetApp.getActiveSheet();
  var rg = sh.getRange("A2:H"   sh.getLastRow());
  var vs = rg.getValues();
  var uA = [];
  var o = [];
  vs.forEach((r, i) => {
    if (!~uA.indexOf(r[0])) {
      uA.push(r[0]);
      o.push(r);
    }
  });
  rg.clearContent();
  sh.getRange(2, 1, o.length, o[0].length).setValues(o);
}

CodePudding user response:

I believe your goal is as follows.

  • You want to remove the duplicated rows by checking column "A".

When your script is modified, how about the following modification?

From:

if(row.join() == novaData[j].join()){

To:

if (row[0] == novaData[j][0]) {

Note:

  • In this case, when removeDuplicates is used, the script can be also written as follows.

      function removerDuplicata() {
        var sheet = SpreadsheetApp.getActiveSheet();
        sheet.getRange("A2:H"   sheet.getLastRow()).removeDuplicates([1]);
      }
    

Reference:

  • Related