简体   繁体   English

有效地比较两个大的对象数组并找出差异

[英]Compare two large arrays of objects effectively and find the differences

I have two large array of objects like: 我有两大类对象,如:

const array1 = [
    {
        userId: 83232932,
        name: 'Tom',
        profile_pic: 'http://..',
        age: 24,
        gender: 'F'
    },
    {
        userId: 2413535,
        name: 'Sam',
        profile_pic: 'http://..',
        age: 31,
        gender: 'M'
    }
]

and another almost equal array. 和另一个几乎相同的阵列。

These two arrays can also have thousands of objects, for example 20k. 这两个数组也可以有数千个对象,例如20k。

I have to compare them and find the objects that are in the first array but not in the second one 我必须比较它们并找到第一个数组中的对象而不是第二个数组中的对象

Now i'm doing: 现在我在做:

const missing = array1.filter(function(item1) {
    return !array2.some(function(item2) {
        return item1.userId === item2.userId;
    });
});

This works, but it blocks the UI of my app for a few seconds. 这可行,但它会阻止我的应用程序的UI几秒钟。

Is there a better way to filter the array or should I review how and when to make this comparison? 有没有更好的方法来过滤数组或者我应该检查如何以及何时进行此比较?

You could take a Set and check against for filtering the first array. 你可以采取一个Set并检查过滤第一个数组。

const
    ids = new Set(array2.map(({ id }) => id)),
    missing = array1.filter(({ id }) => !ids.has(id));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM