javascript underscore.js 过滤一个对象数组,基于另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15103511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
underscore.js filter an array of objects, based on another
提问by bsr
I am trying to filter an array of objects, based on another. The common property 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.
我正在尝试根据另一个对象过滤一组对象。公共属性 id id
。我不确定 filter + each 是最好的方法还是 map reduce。无论如何,下面的代码不能像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);
回答by kay - SE is evil
Just create a "set" of the valid ids and use that "set" to do the filtering:
只需创建一个有效 ID 的“集合”并使用该“集合”进行过滤:
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 * amortizedO(1), i.e O(n). Same holds for the filtering.
填充ids
很快,它在 n *摊销O(1) 中,即 O(n)。同样适用于过滤。
If you use each(…)
in the inner loop, you will have O(n2). For bigger data sets this would become very slow. Also the additional nesting make the code more difficult to read/understand at first glance.
如果您each(…)
在内循环中使用,您将获得 O(n2)。对于更大的数据集,这将变得非常缓慢。此外,额外的嵌套使代码乍一看更难以阅读/理解。
See that code snipped in action: http://jsfiddle.net/SMtX5/
看到在行动中剪断的代码:http: //jsfiddle.net/SMtX5/
回答by anhulife
you can use _.find
to filter:
你可以_.find
用来过滤:
_.filter(aaa, function(a){
return _.find(bbb, function(b){
return b.id === a.id;
});
});
回答by Tony Broyez
bbb = bbb.map(_ => _.id) && aaa.filter(_ => bbb.indexOf( _.id ) > -1)
You just need pure JS array functions to do that assuming your use case.
假设您的用例,您只需要纯 JS 数组函数就可以做到这一点。
回答by pktangyue
You can use _.some(list, [iterator], [context])
.
您可以使用_.some(list, [iterator], [context])
.
It returns trueif any of the values in the listpass the iteratortruth test.
如果列表中的任何值通过迭代器真值测试,则返回true。
var out = _.filter(aaa, function(val){
return _.some(this,function(val2){
return val2['id'] === val['id'];
});
}, bbb);
Here is jsfiddle. http://jsfiddle.net/h98ej/
这是jsfiddle。http://jsfiddle.net/h98ej/