使用谷歌应用程序脚本比较 2 个列表并按顺序填充最终列表

时间:2021-05-19 19:41:42

标签: loops for-loop google-apps-script

我有以下格式的 2 个列表。

  array_so_helper:
  [[01-0158969, 315.0], [01-0161045, 699.0], [01-0161046, 41.0], [01-0161047, 45.0]]

  array_so:
  [[01-0158969, null, 315.0, null], [01-0161045, null, 699.0, null], [01-0161047, null, 45.0,null]]

对于array_so_helper 中的每个第一个元素,如果第二个列表(array_so) 中有匹配项,则将array_so 中的相应子列表写入final_list。如果在array_so_helper 中找到但在array_so 中找不到元素,则将其按以下格式写入final_list:

 [01-0161046, null, 41.0, "yes"]

因此 final_list 必须是

 [[01-0158969, null, 315.0, null], [01-0161045, null, 699.0, null],[01-0161046, null, 41.0, "yes"],, [01-0161047, null, 45.0,null]]

我正在尝试使用 2 个 for 循环来做到这一点,如下所示:

 var array_so_final = [];
 for(i=0; i<array_so_helper.length; i++){
   elem = array_so_helper[i][0]
   value = array_so_helper[i][1]
   for(j=0;j<array_so.length;j++){
     elem_helper_0 = array_so[j][0]
     elem_helper_1 = array_so[j][1]
     elem_helper_2 = array_so[j][2]
     elem_helper_3 = array_so[j][3]
     if(elem == elem_helper){
       array_so_final.push([elem_helper_0,elem_helper_1,elem_helper_2,elem_helper_3])
     }
  }
}

如果 array_so_helper 中缺少元素,不确定如何捕获。

任何线索将不胜感激。

1 个答案:

答案 0 :(得分:1)

您当前的代码中有很多未定义的变量。但是你可以参考这个示例代码:

function compareList() {
  
  var array_so_helper = [['01-0158969', 315.0], ['01-0161045', 699.0], ['01-0161046', 41.0], ['01-0161047', 45.0]];
  var array_so = [['01-0158969', null, 315.0, null], ['01-0161045', null, 699.0, null], ['01-0161047', null, 45.0,null]];
  var array_so_final = [];
 
  for(i=0; i<array_so_helper.length; i++){
    var elem = array_so_helper[i][0]
    var value = array_so_helper[i][1]
    Logger.log(elem);

    //search for the element in the second list
    var search = array_so.find(so =>{
      return so[0]==elem;
    });

    Logger.log(search);
    if(search){
      //match found, add to final list
      array_so_final.push(search);
    }else{
      //match not found
      array_so_final.push([elem, null, value, "yes"]);
    }
  }
  Logger.log("**FINAL**");
  Logger.log(array_so_final);
}

它有什么作用?

  1. 循环所有 array_so_helper 并得到它的 elementvalue
  2. 使用 array.find() 在 array_so 中查找 step1 中获得的 element
  3. 如果找到匹配,将匹配的数据添加到array_so_final
  4. 如果未找到匹配项,请使用以下内容创建数据 [element, null, value, "yes"],然后将其添加到 array_so_final

输出:

5:37:58 AM  Notice  Execution started
5:37:59 AM  Info    01-0158969
5:37:59 AM  Info    [01-0158969, null, 315.0, null]
5:37:59 AM  Info    01-0161045
5:37:59 AM  Info    [01-0161045, null, 699.0, null]
5:37:59 AM  Info    01-0161046
5:37:59 AM  Info    null
5:37:59 AM  Info    01-0161047
5:37:59 AM  Info    [01-0161047, null, 45.0, null]
5:37:59 AM  Info    **FINAL**
5:37:59 AM  Info    [[01-0158969, null, 315.0, null], [01-0161045, null, 699.0, null], [01-0161046, null, 41.0, yes], [01-0161047, null, 45.0, null]]
5:37:59 AM  Notice  Execution completed