簡體   English   中英

有效地比較兩個大的對象數組並找出差異

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

我有兩大類對象,如:

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

和另一個幾乎相同的陣列。

這兩個數組也可以有數千個對象,例如20k。

我必須比較它們並找到第一個數組中的對象而不是第二個數組中的對象

現在我在做:

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

這可行,但它會阻止我的應用程序的UI幾秒鍾。

有沒有更好的方法來過濾數組或者我應該檢查如何以及何時進行此比較?

你可以采取一個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