[英]underscore.js filter an array of objects, based on another
I am trying to filter an array of objects, based on another. 我试图基于另一个过滤对象数组。 The common property id id
. 公共属性id id
。 I am not sure filter + each is the best way to do it or map reduce. 我不确定过滤器+每个是最好的方法或映射减少。 Anyway, below code doesn't work as out
is empty list. 不管怎样,下面的代码就无法正常工作out
空单。
var aaa = [
{name: "AAA", id: 845},
{name: "BBB", id: 839},
{name: "CCC", id: 854}
];
var bbb = [
{id: 839},
{id: 854}
];
var out = _.filter(aaa, function(val){
return _.each(this, function(val2){
return val['id'] === val2['id']
});
}, bbb);
Just create a "set" of the valid ids and use that "set" to do the filtering: 只需创建有效ID的“集合”并使用“set”进行过滤:
var aaa = [
{name: "AAA", id: 845},
{name: "BBB", id: 839},
{name: "CCC", id: 854}
];
var bbb = [
{id: 839},
{id: 854}
];
var ids = {};
_.each(bbb, function (bb) { ids[bb.id] = true; });
var out = _.filter(aaa, function (val) {
return ids[val.id];
}, bbb);
Filling ids
is fast, it's in n * amortized O(1), ie O(n). 填充ids
很快,它在n * 摊销的 O(1)中,即O(n)。 Same holds for the filtering. 同样适用于过滤。
If you use each(…)
in the inner loop, you will have O(n²). 如果在内部循环中使用each(…)
,则将具有O(n²)。 For bigger data sets this would become very slow. 对于更大的数据集,这将变得非常慢。 Also the additional nesting make the code more difficult to read/understand at first glance. 此外,额外的嵌套使得代码乍一看更难以阅读/理解。
See that code snipped in action: http://jsfiddle.net/SMtX5/ 看到该代码已截断: http : //jsfiddle.net/SMtX5/
you can use _.find
to filter: 你可以使用_.find
来过滤:
_.filter(aaa, function(a){
return _.find(bbb, function(b){
return b.id === a.id;
});
});
You can use _.some(list, [iterator], [context])
. 您可以使用_.some(list, [iterator], [context])
。
It returns true if any of the values in the list pass the iterator truth test. 如果列表中的任何值通过迭代器真值测试,则返回true 。
var out = _.filter(aaa, function(val){
return _.some(this,function(val2){
return val2['id'] === val['id'];
});
}, bbb);
Here is jsfiddle. 这是jsfiddle。 http://jsfiddle.net/h98ej/ http://jsfiddle.net/h98ej/
bbb = bbb.map(_ => _.id) && aaa.filter(_ => bbb.indexOf( _.id ) > -1)
假设您的用例,您只需要纯JS数组函数即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.