罗达什_.hasIntersection?

Lodash _.hasIntersection?

我想知道两个或多个数组是否有共同项,但我不关心这些项是什么。我知道 lodash 有一个 _.intersection 方法,但我不需要它 运行 通过每个数组的每个项目。相反,我需要类似 _.hasIntersection 的方法,一旦找到第一个常见事件,它就会停止在数组中查找。 lodash 有类似的东西吗?

您可以简单地使用 some and includes:

var hasIntersection = _.some(arr1, _.ary(_.partial(_.includes, arr2), 1));

这种方法可以让您高效地搜索任意数量的数组中的交集。

function hasIntersection() {
    var collections = _.rest(arguments);

    return _.some(_.first(arguments), function(item) {
        return _(collections)
            .chain()
            .map(_.ary(_.partial(_.includes, item), 1))
            .compact()
            .size()
            .isEqual(collections.length)
            .value();
    });
}

hasIntersection() 函数从创建 collections 开始,这些是我们要在其中查找相交值的集合,减去第一个。它 returns some(), which uses the first() 数组参数的值进行迭代,some() 的回调比较传递给函数的所有其他数组。

这是通过包装 collections 并构建调用链来完成的。它在链的末尾使用 chain() to enable explicit chaining because we want to chain isEqual() to size()

我们将 collections 变量(数组的数组)映射到 includes() function. This results in an array of boolean values, true meaning that there's an intersecting value in one of the collections. The next step is to use compact() 以删除错误值。我们剩下的是相交集合的数量。

如果相交集合的数量与collections的长度相同,我们找到了一个跨所有集合相交的值,并且可以退出。这种方法是有效的,因为 some()includes()

存在短路
hasIntersection([ 1, 2 ], [ 2, 3 ]);
// → true

hasIntersection([ 1, 2, 3 ], [ 2, 4, 5 ], [ 2 ]);
// → true

hasIntersection([ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ]);
// → false