Skip to content Skip to sidebar Skip to footer

Lodash _.hasintersection?

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

Solution 1:

You could simply use some and includes:

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

Solution 2:

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

functionhasIntersection() {
    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

Post a Comment for "Lodash _.hasintersection?"