Filter collection (array of objects) based on other array

前端 未结 1 1168
梦毁少年i
梦毁少年i 2020-12-18 15:54

I have the following problem. I wolud like to filter this fruitsCollection based on fruits array. I would like to be the result was that, for example :

             


        
相关标签:
1条回答
  • 2020-12-18 16:24

    On a modern browser, you can use the native filter:

    fruitsCollection.filter(function(fruit) {
      return fruitsToCut.indexOf(fruit.type) === -1;
    } );
    

    Otherwise, you can use the underscore filter in pretty much the same way:

    _.filter( fruitsCollection, function(fruit) {
      return !_.contains(fruitsToCut, fruit.type);
    } );
    

    Also, your fruit names need to be quoted:

    fruitsCollection = [ {name: 'papaya', type: 'egzotic'}, 
                             {name: 'orange', type: 'citrus'}, 
                             {name: 'lemon', type: 'citrus'}
                           ];
    
    0 讨论(0)
提交回复
热议问题