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

前端 未结 12 2142
广开言路
广开言路 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:19

    Using a combination of ideas from several contributors and the latest ES6 goodness, I arrived at

    const array1 = ["Lorem", "ipsum", "dolor"];
    const array2 = ["Lorem", "ipsum", "quick", "brown", "foo"];
    const array3 = ["Jumps", "Over", "Lazy", "Lorem"];
    const array4 = [1337, 420, 666, "Lorem"];
    
    Array.prototype.intersect = function intersect(a, ...b) {
        const c = function (a, b) {
            b = new Set(b);
            return a.filter((a) => b.has(a));
        };
        return undefined === a ? this : intersect.call(c(this, a), ...b);
    };
    
    console.log(array1.intersect(array2, array3, array4));
    // ["Lorem"]

提交回复
热议问题