I need a little help to improve a function where I'm populating an array with 4 random different non-repeating recipes objects using the id of the recipes, but I need to add an additional condition where the recipes should be 1 breakfast, 1 lunch, 1 snack and 1 dinner, for example:
example of JSON with recipes
[
{
recipeId: 1,
recipeTypeId: 1, // breakFast
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 2,
recipeTypeId: 2, // lunch
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 3,
recipeTypeId: 3, // snack
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 4,
recipeTypeId: 4, // dinner
"description": "someRecipe",
"img": "someImgBase64",
},
{
recipeId: 5,
recipeTypeId: 1, // breakfast
"description": "someRecipe",
"img": "someImgBase64",
}
]
this is my function:
randomRecipes() {
// previously saved recipes from api
localStorage.getItem('recipesList');
// random generator
const randomIndex = new Set();
const recommendedRandomRecipes: [] = [];
while (randomIndex.size < 4) {
randomIndex.add(Math.floor(Math.random() * recipes.length));
}
randomIndex.forEach(i => recommendedRandomRecipes.push(recipes[Number(i)]));
localStorage.addItem('recommendedRecipes', recommendedRandomRecipes);
this.recipes = recommendedRandomRecipes;
}
the result I want:
recommendedRandomRecipes [1,2,3,4] or [2,3,4,5]
what I don't want
recommendedRandomRecipes [1,2,3,5] // 2 breakfast in the array