且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Google脚本应用删除Google表格中特定列中具有特定值的重复行

更新时间:2023-01-17 18:36:54

我会尝试

function removeDuplicates()
{
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
  var dataRange = sheet.getDataRange();
  var data = dataRange.getValues();
  var indexOfStatusColumn = 4;
  var newData = [];
  data.forEach(function (row, rowI){
    var isDuplicate = false
    if (newData.length)
    newData.forEach(function (dup, dupI)
    {
      if (dup[3] == row[3])
      {
        if (row[indexOfStatusColumn] == "Complete" && dup[indexOfStatusColumn] != "Complete")
          newData[dupI][indexOfStatusColumn] = "Complete";
        isDuplicate = true;
        return (false);
      }
    })
    if (!isDuplicate)
      newData.push(row);
  });
  dataRange = sheet.getRange(2, 1, dataRange.getLastRow() - 1, dataRange.getLastColumn());
  dataRange.clearContent();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

几件事

  1. 我使用forEach()循环更有效
  2. 通过返回false来中断循环,以避免无用地解析所有newData谷底
  3. 当我找到一个副本时,我将执行某些操作
  1. I use forEach()loop it's more efficient
  2. break loop by returning falseto avoid parsing trough all your newDatauselessly
  3. when I find a duplicate I perform some of this actions
  1. 检查是否在data上重复了Complete,而不是在newData
  2. 以这种方式将newData中的值更改为"Complete"(完整)(请注意,如果两行中都有不同的数据,可能会扭曲数据).
  1. Check if duplicate is Complete on data and not on newData if so
  2. change the value in newDatato "Complete" this way it will keep the complete status (be careful if there's different datas on both rows it will probably twist datas).

  • 还要在一定范围内使用clearContent()以避免除去工作表的所有内容,而仅除去工作表的特定部分.在这里,我重建了它以保留标题
  • also use clearContent() from a range to avoid removing all the content of the sheet but only a specific portion of it. Here I've rebuilded it to keep the header
  • 参考

    forEach()

    Tanaike基准

    clearContent()