es6⽅式的结果
2. 数组⾥是对象的
let arr1=[
{
age: 1,
name: "张三"
},{
age: 2,
name: "李四"
},{
age: 3,
name: "王五"
},{
age: 4,
name: "赵六"
}
];
let arr2=[
{
age: 5,
js合并两个数组name: "Li"
},{
age: 6,
name: "judy"
},{
age: 3,
name: "王五"
},{
age: 4,
name: "赵六"
}
];
/
/交集(两个数组相同的数据)
let intersection=[];
arr1.forEach(x=>{
arr2.forEach(y=>{
if(x.age==y.age){//到相同的就push进新的数组
intersection.push(x);
}
});
});
console.log("交集",intersection);
//并集(两个数组的合并,数据都是唯⼀的,不重复)
let union=[...arr1, ...arr2];
arr1.forEach(x=>{
arr2.forEach(y=>{
if(x.age==y.age){//到相同的就删除
union.splice(union.findIndex(item=>item.age==x.age),1);
}
});
});
console.log("并集", union);
//补集(两个数组中除了相同的数据)
let complement=[...arr1, ...arr2];
arr1.forEach(x=>{
arr2.forEach(y=>{
if(x.age==y.age){//到就删除,删除完相同的
complement.splice(complement.findIndex(item=>item.age==x.age),1);
complement.splice(complement.findIndex(item=>item.age==y.age),1);
}
});
});
console.log("补集", complement);
//差集(例如数组1中和数组2中不⼀样的数据)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。