1

i have some issues to randomize an array of objects in a loop.

This is what my code looks like:

        this.mealPlan.days.forEach((day) => {
            day.meals.forEach((mealTime) => {
                console.log('before', mealTime.meals);
                //mealTime.meals = this.shuffleArray(mealTime.meals);
                mealTime.meals = mealTime.meals.sort(function() {
                    return Math.random() - Math.random();
                });
                console.log('after', mealTime.meals);
            });
        });

My Problem: The before and after looks exactly the same.

Does anyone knows why this happens?

Thanks a lot!

Fargho
  • 1,267
  • 4
  • 15
  • 30
  • Note that `.sort` only mutates the original array, it doesn't return a new array – CertainPerformance Dec 07 '18 at 11:07
  • Off topic: that's a really neat way to shuffle an array, using the sort function. I've been doing it for years using a rather large piece of code. :) – Kresimir Dec 07 '18 at 11:09
  • 1
    @Kresimir It's not a *good* way to random-sort an array - it'll be biased towards keeping the elements at the start near the start, and keeping the elements at the end near the end. – CertainPerformance Dec 07 '18 at 18:28
  • @CertainPerformance: on second thought, you are completely right, it will be biased towards the initial state of the array. It's not a good replacement for the Fisher-Yates algorithm. – Kresimir Dec 07 '18 at 18:31

0 Answers0