js 多個數組取交集
阿新 • • 發佈:2021-01-12
兩個陣列取交集:
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]