【问题标题】:How to get only unique values of a 2d array如何仅获取二维数组的唯一值
【发布时间】:2023-03-14 16:18:01
【问题描述】:

我需要从以下二维数组:

[[选项 10, 2.0], [选项 10, 2.0], [选项 9, 1.0], [选项 7, 1.0]]

[[选项 10, 2.0], [选项 9, 1.0], [选项 7, 1.0]]

我发现这篇文章 (Splitting a 2D array using some() , by date, avoiding duplicates. Just want 1 unique email, not row. Where am i wrong here?) 有一种非常有效的获取唯一值的方法,但我不知道如何将其应用于我的情况。

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    您的用例比您引用的更简单。

    例如试试这个:

    function myFunction() {
      var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]];
      var dest = [];
      dest.push(source[0]);
      for(var n = 1 ; n< source.length ; n++){
        if(dest.join().indexOf(source[n].join()) == -1){dest.push(source[n])};
      }
      Logger.log(dest);
    }
    

    【讨论】:

      【解决方案2】:

      因为“独特”并不总是很容易描述,所以我经常使用一种模式,它实际上是 Serge 使用 ES5 数组映射/过滤函数的正确答案的变体。

      经过编辑的版本:

      function hash(arr) {
      
        // in this case the hash method is the same as Serge's Array.join() method,
           but could be customised to suit whatever condition you need to generate
           bespoke comparators such as where `1 + 3` should match `2 + 2`, or where
           particular columns in the array can be omitted
      
        return arr.join();
      }
      
      function myFunction() {
        var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]];
        var hash = source.map(
          function (row) {
            return hash(row);
          }
        );
      
        source = source.filter(
          function (filterRow, i) {
            return hash.slice(0, i).indexOf(hash(filterRow)) < 0;
          }
        );
      
        Logger.log(source);
      }
      

      我仅将其包括在内,因为有时您的比较可能需要稍微调整一下。在您的示例中,这并不重要,这就是 Serge 正确的原因,但我分享了一个潜在的扩展,以供思考何时需要“调整”独特性

      【讨论】:

        最近更新 更多