作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个集合:
集合 A
与 model1
, model2
, model3
, 模型 4
。
集合 B
与 model2
,model3
。
例如:
var model1 = new models.ExModel({id: "1", name: "model1"});
var model2 = new models.ExModel({id: "2", name: "model2"});
var model3 = new models.ExModel({id: "3", name: "model3"});
var model4 = new models.ExModel({id: "4", name: "model4"});
var A = new collections.ExCol([ model1, model2, model3, model4 ]);
var B = new collections.ExCol([ model2, model3 ]);
我想获取 B
中不包含的 A
模型数组。例如,我想获得一个包含 model1
和 model4
的数组。我怎样才能最有效地做到这一点?
我想过两种选择来做到这一点,但我不知道这是否是最好的方法。我认为 Option1 比 Option2 更有效率。
选项 1:
var idsB = B.pluck("id");
var result = A.filter( function(m) { return idsB.indexOf(m.id) === -1; } );
选项 2:
var result = A.filter( function(m) { return !B.contains(m); });
完整示例:http://jsfiddle.net/VH3HU/
谢谢!
最佳答案
使用可以使用下划线方法_.difference
。 http://underscorejs.org/#difference
var results = _.difference(A.models, B.models);
关于javascript - 主干集合 - 如何用其他集合过滤集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243643/
我是一名优秀的程序员,十分优秀!