JS 过滤掉两个数组中对象id值相等的项

const arr1 = [{ id: 1, name: '老二' }];
const arr2 = [{ id: 1, name: '网' }, { id: 2, name: '二位' },{ id: 3, name: '二位' }];
// 第一种
let arr1Ids = arr1.map(item => item.id);
const result = arr2.filter(item => !arr1Ids.includes(item.id));
console.log(result);
// 第二种
const s2 = new Set(arr2.map(x => x.id))
const new1 = arr1.filter(x => !s2.delete(x.id))
const new2 = arr2.filter(x => s2.has(x.id))
console.log(new2)
// 第三种
let ids = []
arr1.filter(item => ids.push(item.id))
const res = arr2.filter(item => ids.indexOf(item.id) == -1)
console.log(res);
// 第四种
 let arr3 = arr2.filter((item1) => {
    return arr1.findIndex((item2) => {
        return item2.id == item1.id
    }) == -1
 })
 console.log(arr3)

// 移除数组对象中id相等多的
const tempOld = [{id:1,name:'向三'},{id:2,name:'周七'} ,{id:1,name:'吴月',}]
const temp = tempOld.reduce( (tempArr: any, item: any) => {
    if (tempArr.findIndex((ele: any) => ele.idCardNumber === item.idCardNumber) === -1) {
        tempArr.push(item)
    }
    return tempArr
}, [])

 

posted @ 2022-07-06 16:30  有只橘猫  阅读(3177)  评论(0编辑  收藏  举报