方法 1:使用 filter
和 some
const array1 = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const array2 = [
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' },
{ id: 5, name: 'Eve' }
];
const commonObjects = array1.filter(obj1 =>
array2.some(obj2 => obj1.id === obj2.id)
);
// 需要id-直接后面链式map
console.log(commonObjects);
方法 2:使用 filter
和 includes
(适用于简单的值)
如果两个数组中每个对象是简单的值,可以使用 includes
来筛选出相同的对象。例如:
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const commonElements = array1.filter(value => array2.includes(value));
console.log(commonElements); // 输出 [3, 4, 5]
// 只需要id
const array1 = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const array2 = [
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' },
{ id: 5, name: 'Eve' }
];
const array2Ids = array2.map(obj => obj.id);
const commonIds = array1
.map(obj => obj.id)
.filter(id => array2Ids.includes(id));
console.log(commonIds); // 输出 [3]
方法 3:使用 reduce
和 Map
提高性能
对于大数组,使用 Map
来提高查找性能:
const array1 = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const array2 = [
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' },
{ id: 5, name: 'Eve' }
];
const map = new Map(array2.map(obj => [obj.id, obj]));
const commonObjects = array1.reduce((acc, obj) => {
if (map.has(obj.id)) {
acc.push(obj);
}
return acc;
}, []);
console.log(commonObjects);