Randomly shuffle a Javascript array using the Fisher-Yates algorithm

Quickly shuffle a javascript array while maintaining an even probability of randomness among your results.

Last updated on 16 March, 2023, 11:23pm by keston

Preface

Today I was working a webapp and needed to randomly order an array of objects so that a food menu would show different options each time a user loaded it. You might think there's a standard built in Javascript Shuffle() method to do this but at the time of writing there isn't. 

The maths behind the solution is simple but conceptually fairly complex, luckily I stumbled cross the Fisher-Yates Algorithm which helps us handle this quite succinctly.

Fisher-Yates Algorithm

Checkout the code below which wraps the algorithm in a function that you can call and pass an array to.

Feel free to copy and paste this into a script tag, within a new HTML page - to test locally on your machine and observe how the browser console logs change when you reload the page.

                        


        var points = [{'40' : 3}, {100: 34}, {2:1}, {'5' : 'five'}, {25: 'twenty-five'}, {10: 10}];
        
        function randomiseArray (list) {
            for (let i = list.length -1; i > 0; i--) {
            let j = Math.floor(Math.random() * (i+1));
            let k = list[i];
            list[i] = list[j];
            list[j] = k;
            }
        console.log(list);
        }

        // past this function my array
        randomiseArray(points)
  

In Summary

If you're pushed for time, you're welcome in advance.

Otherwise, you can check out a more detailed explanation for how this works at https://www.w3schools.com/js/js_array_sort.asp

 

Keston