简体   繁体   English

按数组下划线JS过滤数组

[英]Filter array by array Underscore JS

I'm trying to filter out "Players" by their TeamID which is an array, based on the selected checkboxes in a multi-select ( Bootstrap Multiselect to be precise ). 我试图根据多选( 准确地说是Bootstrap Multiselect)中选中的复选框,通过作为数组的TeamID过滤掉“玩家”。

I had it working but the requirements changed and players can be in multiple teams. 我已经开始运作了,但是需求改变了,并且玩家可以在多个团队中。 (I'm sorry I have no JSFiddle / CodePen, Bootstrap Multiselect has no CDN and both of them aren't playing nice) (对不起,我没有JSFiddle / CodePen,Bootstrap Multiselect没有CDN,而且它们都不能很好地播放)

This is what I had for individual teams which worked. 这就是我为各个团队工作的经验。

var temp = [];

_.each(selected, function(i){
            temp.push(_.filter(allPlayers, function(obj){
                return obj.TeamID == i;
            }));
});

However I need to filter an array by an array. 但是我需要按数组过滤数组。

JSON JSON格式

var allPlayers = [{
     "TeamID": [100001, 100002],
     "PlayerID": 1,
     "PlayerName" : "Pete Tong"
    },
    {
     "TeamID": [100001, 100002],
     "PlayerID": 2,
     "PlayerName" : "Will Chamberlain"
    },
    {
     "TeamID": [100002, 100003],
     "PlayerID": 3,
     "PlayerName" : "Jane Doe"
    },
    {
     "TeamID": [100004],
     "PlayerID": 4,
     "PlayerName" : "John Doe"
}];

I've tried Filter two different structured arrays underscore js but it doesn't seem to work for my solution. 我已经试过在js底下过滤两个不同的结构化数组,但是它似乎不适用于我的解决方案。

Selected Array 选定阵列

 var teams = $('#team-list option:selected');
 var selected = [];

 $(teams).each(function(index, team){
        selected.push($(this).val());
 });

This should work: 这应该工作:

var temp = [];

_.each(selected, function(i){
            temp.push(_.filter(allPlayers, function(obj){
                return obj.TeamID.indexOf(i) !== -1;
            }));
});

Rather than comparing if the TeamID equals the selected id, you can check if the TeamID array contains the selected id. 您可以检查TeamID数组是否包含选定的ID,而不是比较TeamID是否等于选定的ID。

if you use filter(), you don't need an extra outside variable: 如果使用filter(),则不需要额外的外部变量:

var allPlayers = [{
     "TeamID": [100001, 100002],
     "PlayerID": 1,
     "PlayerName" : "Pete Tong"
    },
    {
     "TeamID": [100001, 100002],
     "PlayerID": 2,
     "PlayerName" : "Will Chamberlain"
    },
    {
     "TeamID": [100002, 100003],
     "PlayerID": 3,
     "PlayerName" : "Jane Doe"
    },
    {
     "TeamID": [100004],
     "PlayerID": 4,
     "PlayerName" : "John Doe"
}];



var selected=[100003, 100004]; // change this 

var filtered= allPlayers.filter(function(a){
    return selected.some(function(team){
      return a.TeamID.indexOf(team)!==-1;
    });
});

alert(JSON.stringify(filtered, null, "\t"));

demo: http://pagedemos.com/qejbsz722hs3/2 演示: http : //pagedemos.com/qejbsz722hs3/2

edit: added many to many searching. 编辑:增加了许多搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM