1

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.

2
  • I think you should delete the node.js tag, nothing about this question is specific to node.js Commented Sep 17, 2018 at 11:30
  • Ok, and what have you tried? You are expected to at least try then we can help with issues if you have them. Commented Sep 17, 2018 at 11:34

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.