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]
廣告