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

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

    I wrote a helper function for this:

    function intersection() {
      var result = [];
      var lists;
    
      if(arguments.length === 1) {
        lists = arguments[0];
      } else {
        lists = arguments;
      }
    
      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(result.indexOf(currentValue) === -1) {
            var existsInAll = true;
            for(var x = 0; x < lists.length; x++) {
              if(lists[x].indexOf(currentValue) === -1) {
                existsInAll = false;
                break;
              }
            }
            if(existsInAll) {
              result.push(currentValue);
            }
          }
        }
      }
      return result;
    }
    

    Use it like this:

    intersection(array1, array2, array3, array4); //["Lorem"]
    

    Or like this:

    intersection([array1, array2, array3, array4]); //["Lorem"]
    

    Full code here

    UPDATE 1

    A slightly smaller implementation here using filter

提交回复
热议问题