一、交集的定義
數組是JavaScript中最常用的數據類型之一。在實際開發中,我們常常需要理解和使用數組的交集,即兩個數組中共同存在的元素。
交集可以簡單地理解為兩個數組中相同的元素組成的一個新數組。
二、如何求交集
1. 雙重循環遍歷
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const intersection = [];
for(let i = 0; i < arr1.length; i++) {
for(let j = 0; j < arr2.length; j++) {
if(arr1[i] === arr2[j]) {
intersection.push(arr1[i]);
break;
}
}
}
console.log(intersection); // [3, 4, 5]
雙重循環是一種可以解決問題的方法,但是演算法複雜度為 O(n^2),如果數組大小增加,時間複雜度也會呈指數級增長,不是一種好的方法。
2. 使用Set數據結構
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const set1 = new Set(arr1);
const intersection = [...new Set(arr2.filter(num => set1.has(num)))];
console.log(intersection); // [3, 4, 5]
這種方法使用了ES6的Set數據結構,它是一種不重複元素的集合,可以用來消除數組中的重複元素。
先將其中一個數組轉換為Set,再使用filter方法迭代另一個數組,返回包含在第一個Set集合中的元素,最後將新的Set集合轉換為數組。
3. 使用Reduce方法
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const intersection = arr1.reduce((pre, cur) => {
return arr2.indexOf(cur) > -1 && pre.indexOf(cur) === -1 ? pre.concat(cur) : pre;
}, []);
console.log(intersection); // [3, 4, 5]
這種方法使用了reduce方法進行數據處理。初始值為一個空數組,遍歷第一個數組,如果當前值在第二個數組中存在且結果數組中不存在,則將該值添加到結果數組中。
三、應用場景
1. 數據去重
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4, 5]
由於Set數據結構的特性,可以使用Set去重,省去其他去重處理的步驟。
2. 數組交集統計
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const intersection = arr1.reduce((pre, cur) => {
return arr2.indexOf(cur) > -1 && pre.indexOf(cur) === -1 ? pre.concat(cur) : pre;
}, []);
const count = intersection.length;
console.log(count); // 3
在兩個數組中查找存在的共同元素,並計算交集的數量。
四、總結
數組交集是JavaScript中常見的操作之一,求交集的方法有很多,可以根據實際情況靈活選擇。
在實際應用中,可以使用交集對數據進行去重或統計,方便快捷,提高效率。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/179944.html