I have the following issue. There's a problem I have to solve.
Fruit or Vegetable Write a JS function to print "fruit" , "vegetable" or "unknown" depending on the input string.
Fruits are: banana, apple, kiwi, cherry, lemon, grapes, peach
Vegetable are: tomato, cucumber, pepper, onion, garlic, parsley
All others are unknown
The input comes as array of one string element, the name of the fruit. The output should be printed to the console.
Example: input ['banana'] output: fruit
Example: input ['cucumber'] output: vegetable
Example: input ['pizza'] output: unknown
and I've tried something like that.
function fruitOrVegetable(inputArr) {
var fruits = ['banana', 'apple', 'kiwi', 'cherry', 'lemon', 'grapes', 'peach'];
var vegetables = ['tomato', 'cucumber', 'pepper', 'onion', 'garlic', 'parsley'];
for (var i = 0; i < inputArr.length; i++) {
for (var j = 0; j < fruits.length; j++) {
for (var k = 0; k < vegetables.length; k++) {
if (inputArr[i] === fruits[j]) {
return ' fruit ';
} else if (inputArr[i] === vegetables[k]) {
return 'vegetable';
} else {
return 'unknown';
}
}
}
}
}
console.log(fruitOrVegetable(['tomato'])); //Returns vegetable
console.log(fruitOrVegetable(['banana'])); //Returns fruit
console.log(fruitOrVegetable(['cucumber'])); //Returns unknown
console.log(fruitOrVegetable(['pizza'])); // Returns unknown
console.log(fruitOrVegetable(['appple'])); //Returns unknown
Don't know why , but it works only for the 0 index of the array , for example , for 'tomato' it returns vegetable , but if I try it for the other vegetables , it returns unknown. If I remove that last statement
else{
return false;
}
Then , cucumber becomes vegetable , but apple gots undefined? I'm a bit confused , so I'll be glad if someone explain me why this happens. Thank you.
You're doing a massive nested unnecessary
for loop
there. The task is pretty straightforwardYou just have to grab that first
inputArr
value, which is a string and check if its value actually in yourfruits
,vegetables
or elseunknown
.Something like,
Edit:
Let's break the code above,
And returning,
val
exists infruits
, if it does, return 'fruit' or else run 2val
exists invegetables
, if it does, return 'vegetables' or else run 3This operation equals to,
More info:
?:
is a conditional (ternary) operator. (Read more here). It's pretty handy to evaluate expressione.g.
indexOf
is an array native function, which you can check the index of a value in an array. (Read more here)e.g.