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

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

    Small recursive divide and conquer solution that does not rely on es6 or any library.

    It accepts an array of arrays which makes the code shorter and allows you to pass arguments by using map.

    function intersection(a) {
        if (a.length > 2)
            return intersection([intersection(a.slice(0, a.length / 2)), intersection(a.slice(a.length / 2))]);
    
        if (a.length == 1)
            return a[0];
    
        return a[0].filter(function(item) {
            return a[1].indexOf(item) !== -1;
        });
    }
    
    var list1 = [ 'a', 'b', 'c' ];
    var list2 = [ 'd', 'b', 'e' ];
    var list3 = [ 'f', 'b', 'e' ];
    console.log(intersection([list1, list2, list3]));

提交回复
热议问题