javascript - Compare two large arrays of objects effectively and find the differences - Stack Overflow

I have two large array of objects like:const array1 = [{userId: 83232932,name: 'Tom',profile_

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.

I have to pare 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.

Is there a better way to filter the array or should I review how and when to make this parison?

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.

I have to pare 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.

Is there a better way to filter the array or should I review how and when to make this parison?

Share Improve this question asked Sep 6, 2018 at 10:37 IlarioIlario 6,0792 gold badges34 silver badges46 bronze badges 2
  • 1 use the plain old for-loop which is always faster than using the functional approach. That is some optimization in the margin. You cannot beat worst case O(N x M) anyways. A save approach is to use the Worker API for intensive tasks. – KarelG Commented Sep 6, 2018 at 10:42
  • @KarelG I will certainly try the old for-loop and see if there will be any difference – Ilario Commented Sep 6, 2018 at 10:47
Add a ment  | 

1 Answer 1

Reset to default 8

You could take a Set and check against for filtering the first array.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745481322a4629569.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信