How to randomize (shuffle) a JavaScript array?


In this tutorial, we will learn the methods to randomize or shuffle a JavaScript array.

We can achieve this by using existing shuffle functions in some libraries or algorithms.

Let’s move forward to discuss this.

Using the Fisher-Yates Algorithm and Destructuring Assignment

Here, the algorithm iterates through the array from the last index to the first index. In each looping, it swaps the array values and creates a random permutation of a finite sequence.

We can follow the syntax below for using this algorithm.

Syntax

for (var i=arr.length – 1;i>0;i--) {
   var j = Math.floor(Math.random() * (i + 1));
   [arr[i], arr[j]] = [arr[j], arr[i]];
}

Here, the destructuring assignment syntax is used for swapping the values of two variables inside the loop.

Algorithm

  • STEP 1 − List from 1 to N.

  • STEP 2 − Choose a random value x between one and the remaining.

  • STEP 3 − Put the xth value from the last in a new list and eliminate the xth value from the actual list.

  • STEP 4 − Repeat step 2 until all values are eliminated from the list.

  • STEP 5 − The new list in step 3 is a random permutation of the actual list.

Example

In this code, we are swapping the values of two variables in one line of code. Based on the Fisher-Yates algorithm, our program shuffles the input array and displays the output.

<html> <body> <p id = "data"></p> <p id="result"></p> <script> function fisherYatesRandomize(arr) { for (var i = arr.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } var fshArray = [10, 20, 30, 40, 50, 60]; document.getElementById("data").innerHTML = "Original Array - " +fshArray document.getElementById("result").innerHTML = "Shuffled Array - " + fisherYatesRandomize(fshArray); </script> </body> </html>

Using Drustenfield shuffle

Drustenfield’s algorithm is an optimized version of the Fisher-Yates algorithm.

The algorithm picks a random value for each array index and excludes this value from the next pick. This works exactly like picking from a deck of cards. This looping works backward. So, efficiency is optimal here. O(n) is the runtime of this algorithm.

Users can follow the syntax below to use this algorithm.

Syntax

for (var i = arr.length - 1; i > 0; i--)
{
   var j = Math.floor(Math.random() * (i + 1));
   var temp = array[i];
   array[i] = array[j];
   array[j] = temp;
}

Here, swapping is done with the help of a new variable inside the loop.

Algorithm

  • STEP 1 − Let the array length be len

  • STEP 2 − Loop from values of the indexes len-1 and one. Decrement loop control lc.

  • STEP 3 − Select a random value n from current lc and one.

  • STEP 4 − Swap the values of indexes n and lc. Hence the random value moves towards the next iteration indexes.

  • STEP 5 − Continue step 2 and the next steps until the loop is over.

Example

In this example, we give the array to the loop. The Math.random() and general swapping works inside the loop from the last index to the first index. The shuffled array is returned after the loop execution.

<html> <body> <h3> Shuffle a JavaScript array using <i>Drustenfield shuffle algorithm</i> </h3> <p id="data"></p> <p id="result"></p> <script> function doShuffle(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } var drsArr = [100, 200, 300, 400, 500, 600]; document.getElementById("data").innerHTML = "Original Array - " + drsArr document.getElementById("result").innerHTML = "Shuffled Array - " + doShuffle(drsArr); document.getElementById("result").innerHTML = "Shuffled Array - " + doShuffle(drsArr); </script> <p> Note: You may get different shuffled array each time when you run the program </body> </html>

Using the Array sort() Method

Here, we shall discuss the sort() method. Sort is dependent on the JavaScript Engine. The Math.random() value can be positive or negative on every execution. This returns a value between 0 and 0.999. Math.random() – 0.5 returns a value between -0.5 and 0.499.

When the result of the sort of value1 and value2 is greater than 0, value1 is placed before value2. This is the logic.

The sort method modifies the original array. If you need a copy of the original array, you can use the spread operator syntax given below.

Syntax

arr.sort(function(a, b)
{
   return Math.random() - 0.5;
});

//Arrow function syntax
arr.sort(() => Math.random() - 0.5);

//The spread operator syntax
[...arr].sort(() => Math.random() - 0.5);

Usually, two values of the array are passed to the sort function, like in the first syntax. Because we don’t use it inside the function, we can eliminate the parameters.

Example

In this example, the sort method sorts the input array values in a random order using Math.random() – 0.5 logic.

<html> <body> <h3>Shuffle a JavaScript array using the <i>array sort()</i> method</h3> <p id="data"></p> <p id="result"></p> <script> let srtLst = [1, 2, 3, 4, 5, 6, 7]; document.getElementById("data").innerHTML = "Original Array - " + srtLst srtLst = srtLst.sort(() => Math.random() - 0.5); document.getElementById("result").innerHTML = "Shuffled array - " + srtLst; </script> <p>Note: You may get different shuffled array each time when you run the program</p> </body> </html>

Using underscore.js/Lo-Dash library

We will see how to implement this library method in our program. We don’t need any algorithm here. This library has the _.shuffle() method. First, we will import the library in the script tag.

Syntax

_.shuffle(arr);

Here, the input array is given to the shuffle method of this library.

Parameters

  • arr − The input array

Example

In this program, we have added a library file. The shuffle method processes our input array and displays the shuffled array.

<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> </head> <body> <h3> Shuffle a JavaScript array using <i>Underscore js library</i> </h3> <p id="libShuffOp"></p> <script> var libArray = ["Green", "Blue", "White"]; libResArray = _.shuffle(libArray); document.getElementById("libShuffOp").innerHTML = "Shuffled array - " + libResArray; </script> </body> </html>

This tutorial helped us to learn two algorithms methods, the array sort method and a JavaScript library method to randomize the JavaScript array.

The Drustenfield algorithm approach is efficient, fast, and reliable. The array sort method is not reliable because there is no clear pattern. The Underscore.js library increases the load, so prefer this as the final option.

Updated on: 06-Sep-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements