Lodash _.hasIntersection?

北战南征 提交于 2019-12-05 14:39:17

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();
    });
}

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.

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.

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.

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

You could simply use some and includes:

var hasIntersection = _.some(arr1, _.ary(_.partial(_.includes, arr2), 1));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!