使用Underscore.JS合并两个集合 [英] Merging two collections using Underscore.JS

查看:1113
本文介绍了使用Underscore.JS合并两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个集合:



c1 - [{a:1},{a:2},{a:3} ]





c2 - [{a :1},{a:7},{a:8}]



从<$ c添加唯一商品的最快方法是什么$ c> c2 进入 c1 使用 Underscore.JS ?收藏中的实数将是 2K c1 500 对于 c2 ,操作经常执行,因此必须具有高性能!



更新1 - 我只使用 Underscore.JS 几天,我找不到将一个集合添加到另一个集合的方法(我可以过滤 c2 我自己) - 在 Underscore.JS 中是微不足道的?

解决方案

以下将:




  • 创建一个包含c1和c2所有元素的新数组。请参见 union

  • 从该混合中创建一个仅包含唯一元素的新数组。请参阅 uniq



<请注意,只有当您的所有对象都具有 a 属性时才会有效。

  _ .uniq(_。union(c1,c2),false,function(item,key,a){return item.a;}); 

您可以在这个问题


Provided I have two collections:

c1 - [{a:1},{a:2},{a:3}]

and

c2 - [{a:1},{a:7},{a:8}]

what's the fastest way to add unique items from c2 into c1 using Underscore.JS? The real numbers in collections would be 2K for c1 and 500 for c2, the operation is performed often, so must be performant!

Update 1 - I'm only using Underscore.JS for a few days, I couldn't find a way to add one collection into another (I can filter c2 myself) - is that trivial in Underscore.JS?

解决方案

The following will:

  • create a new array that contains all the elements of c1 and c2. See union.
  • from that mix, create a new array that contains only the unique elements. See uniq.

Note that this would work only if all your objects have the property a.

_.uniq(_.union(c1, c2), false, function(item, key, a){ return item.a; });

You can find other options in this question.

这篇关于使用Underscore.JS合并两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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