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

const arr1=[{id:1,name:'网'},{id:2,name:'二位'}]
const arr2=[{id:1,name:'老二'},{id:3,name:'老三'}]

es6方法过滤掉arr2中id和arr1 id相同的项

阅读 20.5k
5 个回答

我自己来分享个

 let arr1=[{id:1,name:'网'},{id:2,name:'二位'}]
 let arr2=[{id:1,name:'问问'},{id:3,name:'多少'},{id:44,name:'多少'},{id:45,name:'多少'},]

  let add=arr2.filter(item=>!arr1.some(ele=>ele.id===item.id))
  console.log(add)
const arr1 = [{ id: 1, name: '网' }, { id: 2, name: '二位' }];
const arr2 = [{ id: 1, name: '老二' }, { id: 3, name: '老三' }];
// 获取到arr1的所有id集合
let arr1Ids = arr1.map(item => item.id);
// 过滤arr2中不包含arr1相同的id数组。
const result = arr2.filter(item => !arr1Ids.includes(item.id));
console.log(result); // [{id: 3, name: "老三"}];

供参考

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))

楼上答案更佳

const arr1 = [{ id: 1, name: '网' }, { id: 2, name: '二位' }]
const arr2 = [{ id: 1, name: '老二' }, { id: 3, name: '老三' }]
let ids = []
arr1.filter(item => ids.push(item.id))
const result = arr2.filter(item => ids.indexOf(item.id) == -1)
    let arr3 = arr2.filter((item1) => {
      return arr1.findIndex((item2) => {
        return item2.id == item1.id
      }) == -1
    })
    console.log(arr3)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题