0

I am looking for a Google Sheets script that will delete anything after the first instance of a duplicate row but only search column B. I found the following script on here but it only addresses duplicate rows that are back to back. For example if cell B5, B7, and B15 all had the same content I would like it to deleted Row 7 and Row 15. Any help is much appreciated.

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getLastRow();
  var firstColumn = sheet.getRange(2, 2, rows, 1).getValues();
  for (var i = rows; i >= 2; i--) {
    if (firstColumn[i-1][0] == firstColumn[i-2][0]) {
      sheet.deleteRow(i);
    }
  }
}
1

Try changing from

var firstColumn = sheet.getRange(2, 2, rows, 1).getValues();
  for (var i = rows; i >= 2; i--) {
    if (firstColumn[i-1][0] == firstColumn[i-2][0]) {
      sheet.deleteRow(i);

To

var firstColumn = sheet.getRange(1, 2, rows, 1).getValues();
firstColumn = firstColumn.map(function (e) {return e[0]})
  for (var i = rows; i >0; i--) {
    if (firstColumn.indexOf(firstColumn[i-1]) != i-1) {
      sheet.deleteRow(i);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.