i have a bug somewhere in my code and iam not able to find it.
At first, this is my method:
async getRandomMeals() {
let that = this;
let meals = [];
let recipeList = await this.appData.getRecipeList(); // {title: "someTitle", ...}, {title: "meal",...} from local stroage
let excludedIngredients = await this.appData.getItem("excludedIngredientsArray") || []; // get from local storage
let mealsProfile = await this.appData.getItem("mealsProfile"); // get from local storage
let filterRecipeList = recipeList;
if (excludedIngredients.length > 0) {
filterRecipeList = this.filterRecipeListByExcludes(recipeList, excludedIngredients)
}
for (let i = 0; i <= 6; i++) {
meals.push(mealsProfile);
}
meals.forEach((day) => {
day.forEach((daytime) => {
daytime.meals = filterRecipeList.filter(x => {
return x.daytime.includes(daytime.slug.toLowerCase())
&& x.difficultyNumber <= daytime.difficulty
}).sort(function () { // <-- this dont work
return 0.5 - Math.random()
});
});
});
console.log(meals);
return meals;
}
My problem:
Everything works fine so far, but the meals should be randomized and for some reasons the randomization dont work.
The problem isnt, that i cant randomize the array. The randomize works great itself, but not on this "filterRecipeList" array.
I would be really happy if someone got a hint or something why the randomize stuff dont work.
Edit:
Also this dont work:
filterRecipeList = filterRecipeList.sort(function () {
return 0.5 - Math.random()
});
Edit 2:
I now got a dirty solution, which looks like this:
await this.appData.setItem("tmpMealPlan", mealPlan); // save to local storage
let finalMealPlan = await this.appData.getItem("tmpMealPlan"); // get again from local storage
finalMealPlan.forEach((day) => {
day.forEach((daytime) => {
daytime.meals = daytime.meals.sort(function () {
return 0.5 - Math.random()
}).slice(0,4);
});
});
return finalMealPlan;
For some reason this works fine, but it looks aweful :D