How to calculate intersection of multiple arrays in JavaScript? And what does [equals: function] mean?

前端 未结 12 2143
广开言路
广开言路 2020-11-29 06:13

I am aware of this question, simplest code for array intersection but all the solutions presume the number of arrays is two, which cannot be certain in my case.

I ha

12条回答
  •  无人及你
    2020-11-29 06:23

    This can be done pretty succinctly if you fancy employing some recursion and the new ES2015 syntax:

    const array1 = ["Lorem", "ipsum", "dolor"];
    const array2 = ["Lorem", "ipsum", "quick", "brown", "foo"];
    const array3 = ["Jumps", "Over", "Lazy", "Lorem"];
    const array4 = [1337, 420, 666, "Lorem"];
    
    const arrayOfArrays = [[4234, 2323, 43], [1323, 43, 1313], [23, 34, 43]];
    
    // Filter xs where, for a given x, there exists some y in ys where y === x.
    const intersect2 = (xs,ys) => xs.filter(x => ys.some(y => y === x));
    
    // When there is only one array left, return it (the termination condition
    // of the recursion). Otherwise first find the intersection of the first
    // two arrays (intersect2), then repeat the whole process for that result
    // combined with the remaining arrays (intersect). Thus the number of arrays
    // passed as arguments to intersect is reduced by one each time, until
    // there is only one array remaining.
    const intersect = (xs,ys,...rest) => ys === undefined ? xs : intersect(intersect2(xs,ys),...rest);
    
    console.log(intersect(array1, array2, array3, array4));
    console.log(intersect(...arrayOfArrays));
    
    // Alternatively, in old money,
    
    var intersect2ES5 = function (xs, ys) {
        return xs.filter(function (x) {
            return ys.some(function (y) {
                return y === x;
            });
        });
    };
        
    // Changed slightly from above, to take a single array of arrays,
    // which matches the underscore.js approach in the Q., and is better anyhow.
    var intersectES5 = function (zss) {
        var xs = zss[0];
        var ys = zss[1];
        var rest = zss.slice(2);
        if (ys === undefined) {
            return xs;
        }
        return intersectES5([intersect2ES5(xs, ys)].concat(rest));
    };
    
    console.log(intersectES5([array1, array2, array3, array4]));
    console.log(intersectES5(arrayOfArrays));

提交回复
热议问题