两个数组去重的JS代码

 

 

const list1 = [
    {id: 0, name: 'xiaomin'},
    {id: 1, name: 'xiaohong'},
];
const list2 = [
    {id: 0, name: 'xiaomin'},
    {id: 1, name: 'xiaohong'},
    {id: 3, name: 'xiaomin'},
    {id: 4, name: 'xiaohong'},
];
// 首先构造Object
const idSet = list1.reduce((acc, v) => {
    acc[v.id] = true;
    return acc;
}, {});
// 遍历list2,去掉在idSet中存在的id
const result = list2.filter(v => !idSet[v.id]);

第二种方法

var result = list2.filter(function(item1) {
     return list1.every(function(item2) {
       return item2.id !== item1.id
     })
 })
 console.log(result);

 

posted @   土小狗  阅读(503)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示