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

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

    Arg0n's answer is great, but just in case anyone is looking for intersection of object arrays, i modified Arg0n's answer a bit to deal with it.

    function getIntersectedData() {
        var lists = [[{a:1,b:2},{a:2,b:2}],[{a:1,b:2},{a:3,b:3}],[{a:1,b:2},{a:4,b:4}]];
        var result = [];
        for (var i = 0; i < lists.length; i++) {
            var currentList = lists[i];
            for (var y = 0; y < currentList.length; y++) {
                var currentValue = currentList[y];
                if (customIndexOf(result,currentValue)) {
                    var existsInAll = true;
                    for (var x = 0; x < lists.length; x++) {
                        if(customIndexOf(lists[x],currentValue)){
                            existsInAll = false;
                            break;
                        }
                    }
                    if (existsInAll) {
                        result.push(currentValue);
                    }
                }
            }
            return result;
        }
    }
    
    function customIndexOf(array,value){
        var notFind = true;
        array.forEach(function(element){
            if(element.a === value.a){
                notFind = false;
            }
        });
        return notFind;
    }
    

提交回复
热议问题