js判断多个数组之间是否存在交集

2023-11-13

代码如下:

//定义一个二维数组,数组中包含N个数组
const arrays = [
  [1, 2, 3],
  [4, 5, 6],
  [2, 7, 8],
  [9, 10, 2]
];
//把数组传入进来
function checkIntersection(arrays) {
  for (let i = 0; i < arrays.length; i++) {
    for (let j = i + 1; j < arrays.length; j++) {
      const setA = new Set(arrays[i]);
      const setB = new Set(arrays[j]);
      const intersection = new Set([...setA].filter(x => setB.has(x)));
      if (intersection.size > 0) {
        return true;
      }
    }
  }
  return false;
}
let isIntersect=checkIntersection(arrays); // true

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

js判断多个数组之间是否存在交集 的相关文章