【问题标题】:Get two arrays, compare and remove duplicates in Google Apps Script获取两个数组,比较并删除 Google Apps 脚本中的重复项
【发布时间】:2018-09-07 06:04:20
【问题描述】:

我在 Google 电子表格中有两个列表:“现有公司”和“新公司”。 我想比较这两者并找出“现有公司”中不存在“新公司”中哪些唯一条目,获取这些条目并从“新公司”中删除所有其他条目。

我已经制作了以下脚本来做到这一点:

function grabNewCompanies() {

  // grab existing companies list from sheet into an array
  var sh = SpreadsheetApp.openById("sheetID").getSheetByName("sheetName")
  var row = sh.getDataRange().getLastRow()
  var existingCompanies = sh.getRange(2,1,row - 1,1).getValues()
  Logger.log(existingCompanies)

//grab new companies added
  var sh = SpreadsheetApp.openById("sheetID").getSheetByName("sheetName")
  var row = sh.getDataRange().getLastRow()
  var newCompanies = sh.getRange(2,4,row - 1, 1).getValues()
  Logger.log(newCompanies)

  var array = [];  
  for(i=0; i<newCompanies.length; i++) {
    for(j=0; j<existingCompanies.length; j++) {
      if(newCompanies[i][0] !== existingCompanies[j][0]) {
      array.push([newCompanies[i][0]]);
}

Logger.log(array)

    }

我已经运行了这个脚本,但它失败了。 正确返回了两个数组(existingCompanies 和 newCompanies)。

但是,两者之间的比较似乎不起作用:它总是返回newCompanies数组的第一个元素,而不管它是否存在于existingCompanies中。

另外,如果newCompanies 包含多个existingCompanies 中不存在的条目,我不确定如何确保推入array 的值不重复。

谢谢。

【问题讨论】:

    标签: arrays google-apps-script comparison


    【解决方案1】:

    您想要检索existingCompanies 和newCompanies 之间的差异元素。如果我对你的问题的理解是正确的,那么这个修改怎么样?我认为您的情况有几种解决方案。因此,请将此视为其中之一。

    修改点:

    • 如果您的脚本被修改,它会从newCompanies 中提取一个元素并检查该元素是否包含在existingCompanies 中。
    • 如果选中的元素不包含在existingCompanies 中,则该元素将被推送到array。在这个修改中,我使用了true 和false 来检查这个。

    重复此流程,直到检查newCompanies 中的所有元素。

    修改脚本一:

    当你的脚本被修改了,这个怎么样?

    从:
    var array = [];  
    for(i=0; i<newCompanies.length; i++) {
      for(j=0; j<existingCompanies.length; j++) {
        if(newCompanies[i][0] !== existingCompanies[j][0]) {
          array.push([newCompanies[i][0]]);
        }
      }
    }
    
    到:
    var array = [];
    for(i=0; i<newCompanies.length; i++) {
      var temp = false; // Added
      for(j=0; j<existingCompanies.length; j++) {
        if(newCompanies[i][0] === existingCompanies[j][0]) { // Modified
          temp = true; // Added
          break; // Added
        }
      }
      if (!temp) array.push([newCompanies[i][0]]); // Modified
    }
    Logger.log(array)
    

    修改脚本2:

    作为其他模式,以下 2 个样本怎么样?这些脚本的处理成本低于使用for循环的脚本。

    var array = newCompanies.filter(function(e) {return existingCompanies.filter(function(f) {return f[0] == e[0]}).length == 0});
    Logger.log(array)
    

    或

    var array = newCompanies.filter(function(e) {return !existingCompanies.some(function(f) {return f[0] == e[0]})});
    Logger.log(array)
    

    如果我误解了你的问题,请告诉我。我想修改它。

    【讨论】:

    • 非常感谢!这正是我所需要的。我最终使用了您建议的成本较低的解决方案之一。谢谢
    • @franciscofcosta 很高兴您的问题得到了解决。也谢谢你。
    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2020-12-14
    • 2021-05-09
    • 2021-12-08
    相关资源
    最近更新 更多