gpt4 book ai didi

javascript - 主干集合 - 如何用其他集合过滤集合?

转载 作者:行者123 更新时间:2023-11-30 13:09:59 25 4
gpt4 key购买 nike

我有两个集合:

  • 集合 Amodel1, model2, model3, 模型 4

  • 集合 Bmodel2model3

例如:

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 模型数组。例如,我想获得一个包含 model1model4 的数组。我怎样才能最有效地做到这一点?

我想过两种选择来做到这一点,但我不知道这是否是最好的方法。我认为 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/

谢谢!

最佳答案

使用可以使用下划线方法_.differencehttp://underscorejs.org/#difference

var results = _.difference(A.models, B.models);

关于javascript - 主干集合 - 如何用其他集合过滤集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com