在实际的项目中,经常会有两个数组获取交集的需求,可采用以下方法实现:
filter
和some
方法const data1 = [{ id: 1, name: 'json' }, { id: 2, name: 'java' }, { id: 3, name: 'vue' }, { id: 4, name: 'react' }, { id: 5, name: 'sql' }];
const data2 = [{ id: 2, name: 'java' }, { id: 4, name: 'react' }];
const arr = data1.filter(obj1 =>
data2.some(obj2 => obj2.id === obj1.id)
); //[{ id: 2, name: 'java' }, { id: 4, name: 'react' }]
const set1 = new Set(data1.map(obj => obj.id));
const arr= data2.filter(obj => set1.has(obj.id));
Set数据结构是一种集合,不允许重复值存在
const arr = new Set([1, 2, 3 , 3, 4, 4, 4]);
console.log([...arr]); // [1, 2, 3, 4]
const arr = new Set([1, 2, 3 , 3, 4, 4, 4]);
console.log([...arr]); // [1, 2, 3, 4]
arr.add('5');
console.log([...arr]); // [1, 2, 3, 4, 5]
arr.delete('3');
console.log([...arr]); // [1, 2, 4, 5]
console.log(arr.has('1')); // true
console.log(arr.has('6')); // false
reduce
方法const arr= data1.reduce((result, obj1) => {
if (data2.some(obj2 => obj2.id === obj1.id)) {
result.push(obj1);
}
return result;
}, []);