2013-10-02 146 views
1

我遇到以下问题。我wolud喜欢根据水果数组过滤这个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'} 
         ] 

也许有下划线的功能?

回答

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'} 
         ]; 
+0

谢谢你:) - 它工作很好,我必须再次读取所有这些和erscore功能。 是的,当然我忘了水果名称的引号;) – Agata