方法1:使用?some()
?+?includes()
(適合小數組)
function haveCommonElements(arr1, arr2) {return arr1.some(item => arr2.includes(item));
}// 使用示例
const arrA = [1, 2, 3];
const arrB = [3, 4, 5];
console.log(haveCommonElements(arrA, arrB)); // true
方法2:使用?Set
(適合大數組,性能更優)
function haveCommonElements(arr1, arr2) {const set = new Set(arr2);return arr1.some(item => set.has(item));
}// 使用示例
const arrC = ['apple', 'banana'];
const arrD = ['orange', 'banana', 'grape'];
console.log(haveCommonElements(arrC, arrD)); // true
方法3:使用?filter()
?+?includes()
(直接獲取交集元素)
function getCommonElements(arr1, arr2) {return arr1.filter(item => arr2.includes(item));
}// 檢查是否有交集
const common = getCommonElements([1, 2], [2, 3]);
console.log(common.length > 0); // true
注意事項:
對象/引用類型:以上方法只適用于基本類型(數字、字符串等)。對象比較的是引用地址:
const obj1 = { id: 1 }; const obj2 = { id: 1 }; const arr1 = [obj1]; const arr2 = [obj2];// 錯誤:比較的是引用地址而非內容 console.log(haveCommonElements(arr1, arr2)); // false
需使用
JSON.stringify()
或深度比較(如Lodash的_.isEqual()
)處理對象。性能考慮:
小數組(<1000元素):
includes()
?可滿足需求大數組:使用?
Set
(Set.has()
?的時間復雜度為 O(1))
完整解決方案(支持基本類型):
function haveCommonElements(arr1, arr2) {// 使用 Set 優化性能const set = new Set(arr2);return arr1.some(item => set.has(item));
}// 測試用例
console.log(haveCommonElements([1, 2], [3, 4])); // false
console.log(haveCommonElements(['a', 'b'], ['b'])); // true
console.log(haveCommonElements([], [])); // false
處理對象數組的擴展方案:
// 使用 Lodash 的深比較
import _ from 'lodash';function haveCommonObjects(arr1, arr2) {return arr1.some(item1 => arr2.some(item2 => _.isEqual(item1, item2)));
}// 或使用 JSON.stringify(注意:屬性順序需一致)
function haveCommonObjects(arr1, arr2) {const set = new Set(arr2.map(item => JSON.stringify(item)));return arr1.some(item => set.has(JSON.stringify(item)));
}
根據需求選擇合適的方法:
基本類型:推薦?
Set
?方案(高效簡潔)對象類型:使用 Lodash 等庫的深度比較函數
超大型數組:考慮分塊處理或 Web Worker 避免阻塞