js 多个数组取交集

两个数组取交集:

const intersection = (a, b) => {
  const s = new Set(b);
  return [...new Set(a)].filter(x => s.has(x));
};

用法:

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

 

多个数组取交集:

方案一:循环遍历

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;
}

方案二:实际还是循环遍历,不过代码看上去就简单多了:

let arr = [
      [1, 2, 3, 4],
      [3, 4, 6],
      [4, 5],
      [4, 5, 8, 9],
      [4, 5, 2, 7],
      [4, 5, 3],
      [4, 5, 0],
    ];

arr.reduce((a, b) => a.filter(c => b.includes(c))) // [4]

 

posted @ 2021-01-12 17:13  iTachiLEe  阅读(7427)  评论(0编辑  收藏  举报