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?
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.
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() .
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With