How to Randomize (Shuffle) a JavaScript Array

Working with arrays is common in JavaScript, and sometimes you may need to randomize the order of the elements in an array. This can be useful in scenarios such as creating a randomized quiz or a card game where you want to shuffle the deck. In this article, we will explore different methods to shuffle a JavaScript array.

Method 1: Using the Fisher-Yates Algorithm

The Fisher-Yates algorithm, also known as the Knuth shuffle, is a commonly used algorithm to shuffle an array. This algorithm works by iterating over the array from the last element to the first element and swapping each element with a randomly selected element that comes before it.


            function shuffleArray(array) {
                for (let i = array.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [array[i], array[j]] = [array[j], array[i]];
                }
                return array;
            }
            
            var arr1 = ["a", "b", "c", "d"];
            var shuffledArray = shuffleArray(arr1);
            console.log(shuffledArray);
        

In the above code snippet, we have defined the shuffleArray function which takes an array as input and shuffles its elements using the Fisher-Yates algorithm. We then call this function on the arr1 array and store the shuffled result in shuffledArray. Finally, we log the shuffled array to the console.

Here is an example output:


            ["d", "b", "a", "c"]
        

As you can see, the elements in the original array have been randomly shuffled.

Method 2: Using the sort() method with a random comparison function

Another method to shuffle an array is by using the sort() method with a random comparison function. The sort() method sorts the elements of an array in place based on the provided comparison function.


            function shuffleArray(array) {
                return array.sort(() => Math.random() - 0.5);
            }
            
            var arr1 = ["a", "b", "c", "d"];
            var shuffledArray = shuffleArray(arr1);
            console.log(shuffledArray);
        

In the above code snippet, we define the shuffleArray function which takes an array as input. We then use the sort() method on the array and provide a random comparison function. This comparison function returns a random number between -0.5 and 0.5, causing the sort() method to shuffle the elements randomly.

Here is an example output:


            ["b", "a", "d", "c"]
        

Again, the elements in the original array have been shuffled randomly.

Method 3: Using the lodash library

If you prefer to use a library, you can achieve array shuffling with the help of the lodash library. Lodash is a JavaScript utility library that provides many useful functions, including a function for shuffling arrays.

First, you need to install lodash by including it in your project as a script or by using a package manager like npm:


            <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
            // or
            npm install lodash
        

Once you have lodash installed, you can use the _.shuffle() function to shuffle an array:


            var _ = require('lodash');
            
            var arr1 = ["a", "b", "c", "d"];
            var shuffledArray = _.shuffle(arr1);
            console.log(shuffledArray);
        

In the above code snippet, we first import the lodash library using the require() function. We then call the _.shuffle() function on the arr1 array and store the shuffled result in shuffledArray. Finally, we log the shuffled array to the console.

Here is an example output:


            ["d", "b", "a", "c"]
        

As before, the elements in the original array have been shuffled randomly.

Conclusion

In this article, we discussed different methods to randomize (shuffle) a JavaScript array. We explored the Fisher-Yates algorithm, using the sort() method with a random comparison function, and using the lodash library. These methods give you options for shuffling arrays based on your preference and the requirements of your project. Now you have the tools to shuffle arrays and add an element of randomness to your JavaScript code!