JavaScript 中数组的唯一交集
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/15 21:32:17
我们需要编写一个 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]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

