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;
}
js arguments}
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],
];

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。