【问题标题】:looping two arrays to get unique elements from one array循环两个数组以从一个数组中获取唯一元素
【发布时间】:2023-02-16 22:49:06
【问题描述】:

我有

arr1 = [ 'Account2', 'Account4', 'Account4', 'Account5' ]
and arr2 = [ 'Account2', 'Account4', 'Account7' ]

我想遍历这两个数组并获得一个新数组,其中仅包含arr1中存在但arr2中不存在的元素

所以新数组应该有 arr3 = ['Account5']

我试过这个

for (var i = 0; i < arr1.length; i++) {
    for (var j = 0; j < arr2.length; j++) {
      if (arr1[i] != arr2[j]) {
        arr3.push(arr1[i]);
      }
    } 
  }
  console.log("arr3", arr3);

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    您的代码不正确,因为它会推送 arr1 的每个元素,这些元素不等于 arr2 的任何元素,这将导致重复和不需要的值。

    一种可能的方法是使用标志变量来检查 arr1 的元素是否存在于 arr2 中,如果不存在则仅将其推送到 arr3。例如:

    var arr1 = [ 'Account2', 'Account4', 'Account4', 'Account5' ];
    var arr2 = [ 'Account2', 'Account4', 'Account7' ];
    var arr3 = [];
    
    for (var i = 0; i < arr1.length; i++) {
      var flag = false; // assume the element is not present in arr2
      for (var j = 0; j < arr2.length; j++) {
        if (arr1[i] == arr2[j]) {
          flag = true; // found the element in arr2, set the flag to true
          break; // no need to continue the inner loop
        }
      }
      if (!flag) { // if the flag is still false, it means the element is not present in arr2
        arr3.push(arr1[i]); // push it to arr3
      }
    }
    
    console.log("arr3", arr3); // ["Account5"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多