一种有效的方式来获得对象的两个数组之间的区别? [英] An efficient way to get the difference between two arrays of objects?

查看:90
本文介绍了一种有效的方式来获得对象的两个数组之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的两个数组:

  VAR A = [{ID:20},{ID:15},{ID:10},{ID:17},{ ID:23}];变种B = [{ID:90},{ID:15},{ID:17},{ID:23}];

我想获得这是一个对象,但不是在b中。从这个例子的结果将是:

{ID:20} {ID:10}

由于阵列可能会很大,我需要一个有效的方式来做到这一点。


解决方案

  //使IDS的哈希表B中
VAR投标= {}
b.forEach(函数(OBJ){
    投标[obj.id] = OBJ;
});//返回B中的一个的所有元素,除非
返回a.filter(函数(OBJ){
    返回(obj.id在出价)!;
});

很轻微的补遗:如果列表是非常大的,你希望避免的2个额外内存的因素,你可以在对象存储摆在首位,而不是使用列表一个HashMap,假设ID是唯一的: A = {20:{等:...},15:{等:...},10:{等:...},17:{等:...}, 23:{等:...}} 。我个人这样做。或者:其次,JavaScript的就地所以它不会占用更多的内存排序名单。例如 a.sort((X,Y)=> x.id-y.id)分拣,因为它为O会比上述更差(N日志(N)) 。但是,如果你不得不反正排序呢,有一个O(N)的算法,它包括两个排序列表:即你认为两个列表一起,并多次采取从列表中最左边(最小的)元素(即检查,然后增加从列表中指针/书签你了)。这就像归并排序,但有一点点关怀找到相同的项目......也许讨厌到code。第三,如果名单是传统code,并且希望将其转换为一个HashMap没有内存开销,还可以通过反复突然离开列表,进入包含HashMap的元素这么做元素乘元素。

I have two arrays of objects:

var a = [  {'id': 20},   {'id': 15},   {'id': 10},   {'id': 17},   {'id': 23}  ];

var b = [ {'id': 90},   {'id': 15},    {'id': 17},   {'id': 23}  ];  

I'd like to get objects which are in a, but not in b. Results from this example would be:

{'id': 20} and {'id': 10}.

Because the arrays could be large, I need an efficient way to do this.

解决方案

// Make hashtable of ids in B
var bIds = {}
b.forEach(function(obj){
    bIds[obj.id] = obj;
});

// Return all elements in A, unless in B
return a.filter(function(obj){
    return !(obj.id in bIds);
});

very minor addendum: If the lists are very large and you wish to avoid the factor of 2 extra memory, you could store the objects in a hashmap in the first place instead of using lists, assuming the ids are unique: a = {20:{etc:...}, 15:{etc:...}, 10:{etc:...}, 17:{etc:...}, 23:{etc:...}}. I'd personally do this. Alternatively: Secondly, javascript sorts lists in-place so it doesn't use more memory. e.g. a.sort((x,y)=>x.id-y.id) Sorting would be worse than the above because it's O(N log(N)). But if you had to sort it anyway, there is an O(N) algorithm that involves two sorted lists: namely, you consider both lists together, and repeatedly take the leftmost (smallest) element from the lists (that is examine, then increment a pointer/bookmark from the list you took). This is just like merge sort but with a little bit more care to find identical items... and maybe pesky to code. Thirdly, if the lists are legacy code and you want to convert it to a hashmap without memory overhead, you can also do so element-by-element by repeatedly popping the elements off of the lists and into hashmaps.

这篇关于一种有效的方式来获得对象的两个数组之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆