数组对象取交集、差集

数组对象取交集、差集

let arr1 = [{
     
   id: 1,
   name: "张三"
},{
     
   id: 2,
   name: "李四"
},{
     
   id: 3,
   name: "王五"
}]
let arr2 = [{
     
   id: 1,
   name: "张三"
},{
     
   id: 2,
   name: "李四"
}]

//差集
let arrDiff = [...arr1].filter(x => [...arr2].every(y => y.id !== x.id));
console.log(arrDiff) //[{id: 3,name: "王五"}]

//交集
let arrInter = [...arr1].filter(x => [...arr2].some(y => y.id === x.id));
console.log(arrInter ) //[{id: 1,name: "张三"},{id: 2,name: "李四"}]

你可能感兴趣的:(普通方法)