javascript - 在这种情况下,有没有更好的方法来使用过滤器数组?
问题描述
我正在尝试实现一个返回数组的函数。
目标是过滤一个数组以获取黄色水果,但如果有香蕉则只返回所有香蕉而不是所有黄色水果。
我的问题是是否有另一种方法来增强此功能以避免过滤两次而只需一个过滤器调用。
这只是普通的 Javascript。我可以使用 JS 的最新功能。
let fruits = [
{name: 'Apple', color: 'Red', size: 'Small'},
{name: 'Banana', color: 'yellow', size: 'Medium'},
{name: 'Orange', color: 'orange', size: 'Big'},
{name: 'Mango', color: 'yellow', size: 'Medium'},
{name: 'Guava', color: 'yellow', size: 'Medium'},
];
function getFruitsThatAreYellowButReturnOnlyBananaIfExists(fruits)
{
let yellowFruits = [];
const bananaFruit = fruits.filter(fruit => fruit.name === "Banana")
.map(banana => `I'm a banana ${banana.size}`);
if (bananaFruit.length > 0) {
return bananaFruit;
}
yellowFruits = fruits.filter(fruit => fruit.color === 'yellow')
.map(yellowFruit => `I'm ${yellowFruit.name} my color is yellow , my size is ${yellowFruit.size}`);
return yellowFruits;
}
const fruitsOrBanana = getFruitsThatAreYellowButReturnOnlyBananaIfExists(fruits);
[ "I'm a banana Medium" ]
如果数组中有 a banana
,我期望结果fruits
,以及这样的消息数组:
[ "I'm Mango my color is yellow , my size is Medium", "I'm Guava my color is yellow , my size is Medium" ]
fruits
如果数组中没有香蕉。
解决方案
一种你可以写这个的方法并不花哨,但以后可能很容易理解:
const bananas = [];
const yellowFruits = [];
//Only requires 1 loop.
fruit.forEach(f => {
if (f.name === 'Banana') {
bananas.push(`I'm a banana ${f.size}`);
}
else if (f.color === 'yellow') {
yellowFruits.push(`I'm ${f.name} my color is yellow , my size is ${f.size}`);
}
});
if (bananas.length > 0) {
return bananas;
}
else {
return yellowFruits;
}
推荐阅读
- javascript - ajax symfony中的Concat变量
- if-statement - 如何处理 Vue 中返回未定义错误的渲染错误
- python - win32com winhttp post 请求文件
- python - 多处理队列存储列表列表
- php - 如何显示雇主状态
- chainer - chainer 中的损失函数保持为零
- xcode - 我在我的 xcode 故事板 - 页面视图控制器中删除了*显然*有用的 XML 代码
- xml - 如何从其他站点获取 World Community Grid 团队统计信息?
- asterisk - Asterisk Dialplan:如何检测呼叫是否已成功接听?
- linux - 重命名多个目录中的多个文件