Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

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

like image 279
Ilario Avatar asked Sep 06 '18 10:09

Ilario


People also ask

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do I compare two arrays to each other?

Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object. equals() .

How do I compare two array sizes?

Check if two arrays are equal or not using SortingSort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.


1 Answers

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));
like image 155
Nina Scholz Avatar answered Oct 03 '22 07:10

Nina Scholz