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]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM