JavaScript中数组的唯一交集

我们需要编写一个包含两个数字数组的JavaScript函数,比如说arr1和arr2。该函数应找到数组元素之间的交集。也就是说,出现在两个数组中的元素。

唯一的条件是,如果我们在相交之前遇到了一个元素,即使在两个数组中都再次出现,也不应再次考虑它。

例如-

如果输入数组是-

const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];

那么输出数组应该是-

const output = [1, 3, 7];

但是,顺序并不那么重要,更重要的是不要考虑重复相交。

示例

以下是代码-

const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];
const uniqueIntersection = (arr1, arr2) => {
   const map = new Set();
   const res = [];
   arr1.forEach(el => map.add(el));
   arr2.forEach(el => {
      if (map.has(el)) {
         res.push(el);
         map.delete(el);
      };
   });
   return res;
};
console.log(uniqueIntersection(arr1, arr2));

输出结果

以下是控制台上的输出-

[1, 7, 3]