A GAS to Removes Duplicates based on a column value

23 views
Skip to first unread message

Hussein Osseily

unread,
Feb 14, 2023, 5:12:22 AM2/14/23
to Google Apps Script Community

Good day Everyone,

I have this script that it should remove duplicates (deleting the whole row) based on the value in Column C
If column has the value "Red" 4 for example it should delete 3 rows and keep the unique one (1 time)I tested it with an example, lets say column C has "Red" 10 times the script is deleting 3 rows, then am having to run it again to delete another 4 Rows and then run it again to delete the rest and keep 1 Unique Row.

Appreciate any help here, thanks in advance.

The Script: 

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var data = sheet.getDataRange().getValues();
  var unique = {};
  
  // Loop through the data array and remove all but the first occurrence of each unique value in column C
  for (var i = 0; i < data.length; i++) {
    var value = String(data[i][2]).trim().toLowerCase(); // clean up the value before checking
    if (unique[value]) {
      sheet.deleteRow(i+1);
    } else {
      unique[value] = true;
    }
  }
  
  // Loop through the unique object and remove any duplicates after the first occurrence
  for (var value in unique) {
    var count = 0;
    for (var i = 0; i < data.length; i++) {
      if (String(data[i][2]).trim().toLowerCase() === value) { // clean up the value before checking
        count++;
        if (count > 1) {
          sheet.deleteRow(i+1);
        }
      }
    }
  }
}

Tanaike

unread,
Feb 14, 2023, 7:14:40 AM2/14/23
to Google Apps Script Community
In your situation, how about using a method of "removeDuplicates" of Class Range? When this method is used, a sample script is as follows.


function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  sheet.getDataRange().removeDuplicates([3]);
}

By this modification, when this script is run the duplicated rows are deleted with the column "C". If I misunderstood your expected result, I apologize.

Reply all
Reply to author
Forward
0 new messages