代码之家  ›  专栏  ›  技术社区  ›  franciscofcosta

获取两个数组,比较并删除googleapps脚本中的重复项

  •  1
  • franciscofcosta  · 技术社区  · 6 年前

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

    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 )正确返回。

    然而,两者之间的比较似乎不起作用:它总是返回 新公司 数组,而不管它是否存在于 现有公司

    另外,我也不确定如何确保 array 如果 包含多个中不存在的条目 现有公司 .

    非常感谢。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Tanaike    6 年前

    要检索元素之间的差异 existingCompanies newCompanies . 如果我对你问题的理解是正确的,这次修改怎么样?我认为对你的情况有几种解决办法。所以请把它看作是其中之一。

    修改点:

    • 在脚本被修改的情况下,它从 新公司 它检查是否包含在 .
    • 如果拾取的元素未包含在 现有公司 array . 在这次修改中,我使用了 true false 为了检查这个。

    重复此流程,直到所有元素 新公司 已检查。

    修改脚本1:

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

    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:

    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)