【问题标题】:How to perform union or intersection on an array of arrays with Underscore.js如何使用 Underscore.js 对数组数组执行联合或交集
【发布时间】:2013-04-20 05:12:31
【问题描述】:

我有一个数组数组:

var selected = [[1, 4, 5, 6], [1, 2, 3, 5, 7], [1, 4, 5, 6], [1, 7]];

Underscore.js 有方便的联合和交集方法,但它们可以将每个数组单独作为参数传递。

如果要执行集合操作的数组数量是任意的,我将如何处理?

This question addresses 类似的东西,但它是用于包含对象的数组。

【问题讨论】:

    标签: javascript underscore.js lodash


    【解决方案1】:

    可以使用apply 将任意数量的参数传递给方法。

    对于联合:

    // Outputs [1, 4, 5, 6, 2, 3, 7]
    var selectedUnion = _.union.apply(_, selected);
    

    对于路口:

    // Outputs [1]
    var selectedIntersection = _.intersection.apply(_, selected);
    

    【讨论】:

    • 有什么理由传入 _ 作为第一个参数?我知道它在函数中设置了“this”,但为什么不使用“null”或只使用“this”。在这种情况下,我不能说我完全理解“这个”。
    • 好点。我认为它不会影响此用例中的任何内容。我认为这只是让语句在语义上看起来更好的强迫症。 :)
    • 这很好,但是我们如何在 _.chain 中使用它呢?
    【解决方案2】:

    为什么不使用 reduce

    _.reduce(selected,function(result,a){
        return _.intersection(result,a);
    });
    

    【讨论】:

      【解决方案3】:

      var centrifuge = _.spread(_.intersection);
      
      alert(centrifuge([
        [1, 4, 5, 6],
        [1, 2, 3, 5, 7],
        [1, 4, 5, 6],
        [1, 7]
      ]))
      
      
      alert(centrifuge([
        [1, 4, 5, 6],
        [1, 2, 4, 6, 3, 5, 7]
      ]))
      <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

      var centrifuge = .spread(.intersection);

      【讨论】:

        【解决方案4】:

        我能找到的最简单的方法:_.union(...arrays)

        这适用于 Underscore.js 和 Lodash。

        我能想到的唯一主要缺点是它使用了array spread syntax,这在 Internet Explorer 中不起作用(除非您使用像 Babel 这样的工具来翻译它)。

        【讨论】:

          猜你喜欢
          • 2019-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-18
          • 2023-03-18
          • 1970-01-01
          • 1970-01-01
          • 2021-12-07
          相关资源
          最近更新 更多