我有两个集合:
集合
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/