【发布时间】:2016-05-08 01:04:57
【问题描述】:
我正在研究 javascript-koans,这是 AboutApplyingWhatWeHaveLearnt.js 的第一个挑战。目标是编写函数式代码——给出一个命令式的答案——删除没有蘑菇和坚果的产品,将它们推送到一个新数组,并获取该数组的长度。这是我正在使用的数据集:
products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
{ name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
{ name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
{ name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];
以下是挑战的指导:
使用 filter() & all() / any() 解决
我坚持使用每个内部过滤器(推力、长度等不是问题)。我能够过滤掉没有坚果的条目,并使用每个(所有的别名),使用每个产品的索引搜索每个产品的成分数组,如果数组包含“蘑菇”,则返回真/假。但是,我想使用过滤器的每个内部,所以我不必使用循环。这是我想出的,但它没有返回任何条目:
_.filter(products, function(product) {
if(_.every(product.ingredients, function(ingredient) {ingredient !== "mushrooms"})){
return product;
}
})
我正在尝试做的事情可能吗?非常感谢任何指导。
【问题讨论】:
标签: javascript arrays functional-programming underscore.js