简体   繁体   中英

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 ).

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)

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

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.

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.

if you use filter(), you don't need an extra outside variable:

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

edit: added many to many searching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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