Reputation: 53
I'm building a recipe generator in react.js and es6. Im trying to filter the recipes in a good way and right now I'm just checking if my recipes includes any of the choosen ingredients.
I want it to first check if my Baseingredient is in the recipe-ingredient array and then filter the rest after that is done. So the baseingredient MUST be included.
The baseingredient and the choosen ingredients are all in the same ingredientArray(cartIds), so the "cartIds" also includes the Id of my currentBaseingredient.
This is what my code looks like today.
const recipes = () => {
return { recipes: Store.getRecipes(), cart: Store.getCart(), baseingredient: Store.getCurrentBaseIngredient() }
}
const Recipes = ( props ) => {
var cartIds = props.cart.map(item => item.ingredientId); // Ex: [11, 23, 1]
// TODO: this ingredient-id must be in the recipes ingredient array!!
var baseIngredient = props.baseingredient.ingredientId;
console.log('baseingredient id:',baseIngredient); // Ex: 1
var recipes = props.recipes
.filter(recipe => ( // Run filter function on all recipes
recipe.ingredients.some(ingredient => ( // Check if reciepe contains any of the chosen ingredients
cartIds.indexOf(ingredient.ingredientId) >= 0) // Ingredient check
)
)) // Now we have a list of reciepes which contain some of the chosen ingredients
.map( ( recipes, i ) => {
return (
<RecipesItem
key={i}
recipe={recipes}/>
)
} );
return (
<div>
<table className="table table-hover">
<thead>
<tr>
<th>Recipe</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{recipes}
</tbody>
</table>
</div>
);
}
Upvotes: 2
Views: 582
Reputation: 3198
Is something like below what you need? Also you were missing the return
keyword in your filter before
var recipes = props.recipes
.filter(recipe => ( // Run filter function on all recipes
return recipe.ingredients.includes(baseIngredient) && recipe.ingredients.some(ingredient => ( // Check if reciepe contains any of the chosen ingredients
cartIds.indexOf(ingredient.ingredientId) >= 0) // Ingredient check
)
)) // Now we have a list of reciepes which contain some of the chosen ingredients
.map( ( recipes, i ) => {
return (
<RecipesItem
key={i}
recipe={recipes}/>
)
} );
Upvotes: 1