基于其他数组过滤集合(对象数组)

时间:2013-10-02 06:34:32

标签: javascript arrays collections underscore.js

我有以下问题。我喜欢根据fruits数组过滤这个fruitsCollection。 我希望结果是,例如:

     filteredFruits1 [ all fruits with the 
                       exception of those which are in  
                       fruitsToCut array
                     ]

示例:

var fruitsToCut = [ 'egzotic', 'other'],
    fruitsCollection = [ {name: papaya, type: 'egzotic'}, 
                         {name: orange, type: 'citrus'}, 
                         {name: lemon, type: 'citrus'}
                       ]

也许有一些下划线功能?

1 个答案:

答案 0 :(得分:2)

在现代浏览器上,您可以使用原生filter

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

否则,你可以用几乎相同的方式使用underscore filter

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

此外,您的水果名称需要引用:

fruitsCollection = [ {name: 'papaya', type: 'egzotic'}, 
                         {name: 'orange', type: 'citrus'}, 
                         {name: 'lemon', type: 'citrus'}
                       ];