在这种情况下,有没有更好的方法使用过滤器阵列?

时间:2019-08-28 02:36:22

标签: javascript arrays

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

目标是过滤一个数组以获取黄色水果,但是如果有香蕉,则只需返回所有香蕉而不是所有黄色水果即可。

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

这只是普通的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" ]数组中有一个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数组中没有香蕉。

2 个答案:

答案 0 :(得分:1)

您可以写一种不太花哨的方法,但是稍后可能会很容易理解它:

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;
}


答案 1 :(得分:1)

您可以使用for ... of循环在对象数组上仅迭代一次。迭代时,您可以将Bananas收集到一个数组中,并将黄色的果实收集到另一个数组中。然后,您可以返回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;}