0

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

Fargho
  • 1,267
  • 4
  • 15
  • 30
  • You're randomising the inner `meals` arrays, you should probably call `sort` directly on the `meals` array. – Titus Sep 23 '17 at 09:42
  • Possible duplicate of [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – Marcin Malinowski Sep 23 '17 at 09:42
  • Also filterRecipeList = filterRecipeList.sort(function () { return 0.5 - Math.random() }); dont work :( – Fargho Sep 23 '17 at 09:45
  • Using `0.5 - Math.random()` should work. Check out this JSBin: http://jsbin.com/nusivakeba/edit?js,console. Can you share the output of `console.log(meals)` in the last line? – Gilad Artzi Sep 23 '17 at 09:48

0 Answers0