首页 > 解决方案 > 在这种情况下,有没有更好的方法来使用过滤器数组?

问题描述

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

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

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

这只是普通的 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如果数组中没有香蕉。

标签: javascriptarrays

解决方案


一种你可以写这个的方法并不花哨,但以后可能很容易理解:

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



推荐阅读