gpt4 book ai didi

javascript - 在这种情况下有没有更好的方法来使用过滤器数组?

转载 作者:行者123 更新时间:2023-11-30 13:53:45 24 4
gpt4 key购买 nike

我正在尝试实现一个返回数组的函数。

目标是过滤数组以获得黄色水果,但如果有Banana,则只返回所有香蕉而不是所有黄色水果。

我的问题是是否有另一种方法可以增强此功能以避免过滤两次而只调用一次过滤器。

这只是普通的 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);

如果 fruits 数组中有一个 banana 并且一个像这样的消息数组:

[ "I'm Mango my color is yellow , my size is Medium", "I'm Guava my color is yellow , my size is Medium" ]

如果 fruits 数组中没有香蕉。

最佳答案

您可以使用 for ... of循环只在对象数组上迭代一次。迭代时,您可以将 Bananas 收集到一个数组中,将黄色水果收集到另一个数组中。然后,如果有则返回香蕉数组,否则返回黄色水果数组。

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 = [], bananas = [];

for (const {name, color, size} of fruits)
{
if (name.toLowerCase() === "banana")
bananas.push(`I'm a banana ${size}`);
else if (color.toLowerCase() === "yellow")
yellowFruits.push(`I'm ${name} my color is yellow , my size is ${size}`);
}

return bananas.length ? bananas : yellowFruits;
}

console.log(getFruitsThatAreYellowButReturnOnlyBananaIfExists(fruits));
fruits[1].name = "lemon";
console.log(getFruitsThatAreYellowButReturnOnlyBananaIfExists(fruits));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

关于javascript - 在这种情况下有没有更好的方法来使用过滤器数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com