Reputation:
I have an array that stores user input and I have objects that require specific values to be true.The user input must match the ingredients in each object.
var recipes = [
{
'name': 'Omelette',
'ingredients': [
"Eggs",
"Mushrooms",
"Peppers",
"Onions"
]
},
{
'name': 'Spaghetti',
'ingredients': [
"Pasta",
"Tomato",
"Meat Balls"
]
};
var storedIngredients = [];
//This is the array that stores user input.
//I used this is so far but it's hardcoded and I don't want hardcode
if (storedIngredients.includes('Pasta','Tomato','Meat Balls') {
console.log(recipes.name[0];);
};
I need a way to have if the user enters the corresponding ingredients he will be shown that he has the ingredients to make spaghetti for example.
Upvotes: 1
Views: 636
Reputation: 31
You can use filter on the array to find a list of reciepes which the user has the ingredients for.
var recipes = [
{
'name': 'Omelette',
'ingredients': [
"Eggs",
"Mushrooms",
"Peppers",
"Onions"
]
},
{
'name': 'Spaghetti',
'ingredients': [
"Pasta",
"Tomato",
"Meat Balls"
]
}];
var storedIngredients = ["Pasta",
"Tomato",
"Meat Balls",
"Onions"];
var match = recipes.filter(x => x.ingredients.every(e => storedIngredients.some(s => s === e)));
console.log(match);
Upvotes: 3
Reputation: 2671
You can use reduce on the recipes array, then every recipe the user can make, push it into a new array.
var recipes = [
{
'name': 'Omelette',
'ingredients': [
"Eggs",
"Mushrooms",
"Peppers",
"Onions"
]
},
{
'name': 'Spaghetti',
'ingredients': [
"Pasta",
"Tomato",
"Meat Balls"
]
}]
var storedIngredients = ['Pasta', 'Tomato', 'Meat Balls'];
//This is the array that stores user input.
//I used this is so far but it's hardcoded and I don't want hardcode
let result = recipes.reduce((acc, n) => {
let ingredients = n.ingredients;
if (storedIngredients.includes(...ingredients)) acc.push(n.name);
return acc;
}, [])
console.log(result);
Upvotes: 0