两个数组的交点是指两个数组中共同拥有的元素。例如,数组 [1, 2, 3, 4]
和数组 [3, 4, 5, 6]
的交点是 [3, 4]
。
function findIntersection(arr1, arr2) {
return arr1.filter(value => arr2.includes(value));
}
const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];
console.log(findIntersection(array1, array2)); // 输出: [3, 4]
function findIntersectionByProperty(arr1, arr2, prop) {
const set1 = new Set(arr1.map(item => item[prop]));
return arr2.filter(item => set1.has(item[prop]));
}
const objectsArray1 = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const objectsArray2 = [{id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
console.log(findIntersectionByProperty(objectsArray1, objectsArray2, 'id')); // 输出: [{id: 2, name: 'Bob'}]
原因:当数组非常大时,使用 filter
和 includes
可能会导致性能问题。
解决方法:使用集合(Set)来提高查找效率。
function findIntersectionOptimized(arr1, arr2) {
const set1 = new Set(arr1);
return arr2.filter(value => set1.has(value));
}
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
console.log(findIntersectionOptimized(array1, array2)); // 输出: [5, 6, 7, 8, 9, 10]
原因:在复杂对象数组中,对象的属性名称或结构不一致。
解决方法:确保对象属性一致,或者在比较前进行属性映射。
function findIntersectionByProperty(arr1, arr2, prop) {
const set1 = new Set(arr1.map(item => item[prop]));
return arr2.filter(item => set1.has(item[prop]));
}
const objectsArray1 = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const objectsArray2 = [{user_id: 2, user_name: 'Bob'}, {user_id: 3, user_name: 'Charlie'}];
console.log(findIntersectionByProperty(objectsArray1, objectsArray2, 'id')); // 输出: []
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云