admin管理员组

文章数量:1426620

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

本文标签: javascriptCompare two large arrays of objects effectively and find the differencesStack Overflow