Lodash _.hasIntersection? [英] Lodash _.hasIntersection?

查看:92
本文介绍了Lodash _.hasIntersection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道两个或多个阵列是否有共同的项目,但我不在乎这些项目是什么。我知道lodash有一个 _。intersection 方法,但我不需要它来遍历每个数组的每个项目。相反,我需要像 _。hasIntersection 这样的方法,一旦找到第一个常见的事件就会停止查看数组。 lodash有类似的东西吗?

I want to know if two or more arrays have common items, but I don't care what those items are. I know lodash has an _.intersection method, but I don't need it to run through every single item of each array. Instead, I need something like a _.hasIntersection method that will stop looking in an array once it finds the first common occurrence. Does lodash have something like that?

推荐答案

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

This approach lets you efficiently search for an intersection in an arbitrary number of arrays.

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()函数从创建集合开始,这些是我们想要查找交叉值的集合,减去第一个。它返回 some()的值,该值使用 first()数组参数迭代,回调到 some()比较传递的所有其他数组函数。

The hasIntersection() function starts off by creating collections, these are the collections we want to look for intersecting values in, minus the first one. It returns the value of some(), which uses the first() array argument to iterate over, the callback to some() compares all the other arrays passed to the function.

这是通过包装集合并构建一个调用链来完成的。它使用 chain()来启用显式链接,因为我们想链 isEqual() size() 在链的末尾。

This is done by wrapping collections and building a call chain. It uses chain() to enable explicit chaining because we want to chain isEqual() to size() at the end of the chain.

我们映射集合变量,一个数组数组,到包含()功能。这会产生一个布尔值数组,true表示其中一个集合中存在交叉值。下一步是使用 compact()删除falsey值。我们剩下的是相交集合的数量。

We map the collections variable, an array of arrays, to the 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() to remove falsey values. What we're left with is the the number of intersecting collections.

如果相交集合的数量与集合的长度相同,我们发现了一个跨越所有集合的值,并且可以退出。这种方法很有效,因为 some()包括()

If the number of intersecting collections is the same length as collections, we've found a value that intersects across all collections, and can exit. This approach is efficient because of the short-circuits in place with some() and 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

这篇关于Lodash _.hasIntersection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆