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
1 Answer
Reset to default 8You 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
版权声明:本文标题:javascript - Compare two large arrays of objects effectively and find the differences - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745481322a2660185.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论