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

标签 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'}
                       ]

也许一些下划线功能?

最佳答案

在现代浏览器上,您可以使用 native 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'}
                       ];

关于javascript - 基于其他数组过滤集合(对象数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19131187/

相关文章:

javascript - 检测浏览器是否足够快

javascript - JS onkeydown/onkeyup - 转换为 jQuery keydown/keyup

java - Java foreach 循环每次迭代都会得到一个列表吗

swift - 如何线程安全地归档一组自定义对象?

javascript - Three.js:将 3d 位置转换为 2d 屏幕位置

javascript - 如何在悬停后显示从下到上的下拉菜单 slider 效果?

arrays - 将二维数组绑定(bind)到 Datagrid

arrays - 使用变量在 bash 中传递 grep 模式

C++:使用动态内存创建动态数组

java - 比较两个 HashMap 是否具有相同的值和相同的键集?