How to shuffle array using javascript

A fundamental programming task involves rearranging an array, particularly when randomness is a factor, such as in gaming scenarios or when generating randomized collections. The Fisher-Yates shuffle, frequently referred to as the Knuth shuffle, is an effective algorithm for shuffling an array in JavaScript. The method math.random is employed to randomly organize the elements of the given array.

Overview of Array Shuffling

In JavaScript, it is often essential to shuffle or randomly reorder elements within arrays. This article will explore various methods for shuffling an array in JavaScript, discussing multiple techniques and approaches, including the most efficient and recommended ones.

Rearranging an array's items at random without following a set order is known as shuffling. This is frequently required in a variety of situations, including:

  • arranging a list of elements (such as quiz questions) in a random sequence.
  • rearrange a deck of cards for a game.
  • choosing a examples at random from a input information.

In JavaScript, there are various methods available for shuffling arrays. Employing randomness along with specific algorithms and procedures guarantees that each element has an equal probability of appearing in any given position within the array.

Why Use an Array Shuffle?

The following are some typical use situations where array shuffling is crucial:

  • Games: When playing card games, the deck of cards (represented as an array) may need to be shuffled.
  • Randomization: The method is used for arranging quiz questions in a different sequence. It is worked for arranging text or graphic components in a different order.
  • Sampling: Choosing a random sample from a collection of information points is known as sampling.
  • Simulation: Shuffled information is necessary for randomized simulations with the Monte Carlo simulations.
  • Shuffle Techniques for Arrays

There exist alternative methods for shuffling an array, with the Fisher-Yates shuffle being the most prominent. This technique is recognized as the most effective approach for rearranging the elements of an array.

1. Shuffle JavaScript Array Using Fisher-Yates Shuffle

The Fisher-Yates shuffle, which is often known as the Knuth shuffle, stands out as one of the most widely used and efficient algorithms for permuting an array. This technique is considered the optimal approach for randomizing elements, as it guarantees that each potential arrangement of the array has an equal probability of occurring.

How the Shuffle by Fisher-Yates Works:

The Fisher-Yates shuffle functions by traversing the array starting from the last element down to the second element (moving from right to left). At each location, it swaps the elements by selecting a random index that ranges from the current position to the start of the array.

Explanation:

Let's begin with the final component: Select the array's final element.

  • Select a random index: Select a random index that falls between the first and current positions.
  • Exchange parts: Exchange the element at the random index for the element at the current location.
  • Procedure to the next part: Repeat until you reach the first element, then move on to the next one on the left.

Syntax

The syntax illustrates the Fisher-Yates algorithm utilized for rearranging the elements of an array.

Example

for (let i = array.length - 1; i > 0; i--) {  
    // create random index of the array
    const j = Math.floor(Math.random() * (i + 1)); 
    // Swap the array elements with the i and j variable
    const temp1 = array[i];
    array[i] = array[j];
    array[j] = temp1;
}

Explanation:

  • Using "for loop," we begin the loop from the final element (arr.length—1) and proceed to the first element.
  • Using Math.random, a random number between 0 and 1 is produced.
  • floor: This ensures the random number is between 0 and the current index (i) and is an integer.
  • [arr[i], arr[j]] = [arr[j], arr[i]]; this expression is used to destructure an array by swapping the members at indices i and j.

Examples

The subsequent examples illustrate the shuffled arrays containing either numeric or string elements.

Example 1:

The subsequent illustration demonstrates how to shuffle an array of numbers using the Fisher-Yates Shuffle algorithm in JavaScript.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle number Array Using JavaScript Fisher-Yates Shuffle method.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display Camet case data.</button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given input array
const a = [100, 20, 30, 400, 50, 60, 70];
// Function to use the Fisher-Yates Shuffle
function myFunction(array) {
    // Iterate all the array in reverse order
    for (let i = array.length - 1; i > 0; i--) {
        // Generate Random Index of  arrays
        const j = Math.floor(Math.random() * (i + 1));
        // Swap elements
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
// Get the shuffled array from the javascript function
const a1 = myFunction(a); 
// Display Shuffled array
console.log("Shuffled Array: " +a1);
 document.getElementById("demo").innerHTML = "Shuffled Array: " +a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Example 2:

The subsequent example demonstrates how to shuffle a string array utilizing the Fisher-Yates Shuffle algorithm in JavaScript.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle number Array Using JavaScript Fisher-Yates Shuffle method.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display Camet case data.</button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given input array
const a = ["ram", "sham", "kahna", "parth",  "karan",  "radha", "shiv"];
// Function to use the Fisher-Yates Shuffle
function myFunction(array) {
    // Iterate over the array in reverse order
    for (let i = array.length - 1; i > 0; i--) {
        // Generate Random Index of the arrays
        const j = Math.floor(Math.random() * (i + 1));
        // Swap elements
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
// Get the shuffled array from the javascript function
const a1 = myFunction(a); 

// Display Shuffled array
console.log("Shuffled Array: " + a1);
 document.getElementById("demo").innerHTML = "Shuffled Array: " +a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Example 3:

The subsequent example demonstrates how to shuffle a decimal array utilizing the Fisher-Yates Shuffle algorithm in JavaScript.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle Decimal number Array Using JavaScript Fisher-Yates Shuffle method.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display Camet case data.</button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given input array
const a = [0.2, 1.0, 4.2, 5.6, 8.8]; 
// Function to use the Fisher-Yates Shuffle
function myFunction(array) {
    // Iterate over the array in reverse order
    for (let i = array.length - 1; i > 0; i--) {
        // Generate Random Index of the arrays
        const j = Math.floor(Math.random() * (i + 1));
        // Swap elements
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
// Get the shuffled array from the javascript function
const a1 = myFunction(a); 

// Display Shuffled array
console.log("Shuffled Array: " + a1);
 document.getElementById("demo").innerHTML = "Shuffled Array: "+a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Time Complexity of Fisher-Yates Shuffle

  • The time complexity for the Fisher-Yates shuffle algorithm is O(n), with n representing the length of the array.
  • This method is considered efficient since it processes the array a single time while performing a swap for each individual element exactly once.
  • 2. Applying the array.sort method in JavaScript

To generate a shuffled array, we can utilize a custom comparison function in conjunction with the JavaScript array sort method. The sort function is provided with a comparator function that returns the result of (random value - 0.5).

The random comparator is a commonly used, yet inefficient, approach to shuffling an array via the sort function. While this technique rearranges the array into a random sequence, it does not ensure an even distribution of all possible permutations. Due to the potential for biased outcomes, it is advisable to avoid utilizing this method in production environments.

Syntax

The syntax demonstrates the utilization of the array.sort function in JavaScript for the purpose of randomizing the order of elements within an array.

Example

array.sort( () => Math.random()-0.5 );

Examples

The subsequent examples demonstrate how to shuffle an array containing either numerical or string elements by utilizing the array.sort method in JavaScript.

Example 1:

The subsequent example demonstrates how to shuffle an array of numbers utilizing the array.sort method in JavaScript.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle number Array Using the array.sort() method in JavaScript.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display the shuffle array. </button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given input array
const a1 = [10, 20, 30, 40, 50, 60, 70];

// Shuffle the array using reduce() and math.random() methods
a1.sort(() => Math.random() - 0.5);

// Show the shuffled array in the tab as output
console.log("Shuffled Array: "+a1);

document.getElementById("demo").innerHTML = "Shuffled Array: "+a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Example 2:

The subsequent example demonstrates how to shuffle a string array utilizing the array.sort method in JavaScript.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle number Array Using the array.sort() method in JavaScript.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display the shuffle array. </button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given input array
const a1 = ["ram", "sham", "kahna", "parth",  "karan",  "radha", "shiv"];
// Shuffle the array using reduce() and math.random() methods
a1.sort(() => Math.random() - 0.5);
// Show the shuffled array in the tab as output
console.log("Shuffled Array: " +a1);
document.getElementById("demo").innerHTML = "Shuffled Array: "+a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Challenges with sort in the context of shuffling:

  • Time complexity: Generally, the sorting algorithm operates with a time complexity of O(n log n), making it less efficient compared to the O(n) approach of the Fisher-Yates shuffle, as it is not tailored for randomization.
  • Inconsistent randomness: The resultant shuffled array may exhibit bias due to the reliance of the sorting algorithm on random comparison values, potentially resulting in an uneven distribution of outcomes.
  • 3. Applying the Math.random Method to array.reduce

After the logic for each component has been established, a singular output is generated through the use of the array.reduce function. During each iteration of the reduction process, we have the opportunity to rearrange the elements by utilizing the math.random function.

Syntax

The syntax demonstrates how to utilize the Math.random method in conjunction with the array.reduce method to effectively shuffle an array.

Example

array.reduce( 
    function(total, currentValue, currentIndex, arr), 
    initialValue
)

Examples

The subsequent examples illustrate how to shuffle an array containing numeric or string elements by utilizing the Math.random method in conjunction with the array.reduce method for shuffling the array.

Example 1:

The subsequent illustration demonstrates how to shuffle an array of numbers utilizing the JavaScript random function in conjunction with the reduce method.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle number Array Using JavaScript random and reduce method.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display the shuffle array. </button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given input array
const a = [10, 20, 30, 40, 50, 60, 70];
// Shuffle the array using reduce() and math.random() methods
const a1 = a.reduce(
    (acc, _, i) => {
     
        // Generate a random index with equation
        const random = Math.floor(Math.random() * (acc.length - i)) + i;
        
        // Swap the element with the random index element of the array
        [acc[i], acc[random]] = [acc[random], acc[i]]; 
        
        return acc;
    },
    [...a] // Initialize accumulator as allow a copy of the array
);

// Show the shuffled array in the tab as output
console.log("Shuffled Array: " + a1);
 document.getElementById("demo").innerHTML = "Shuffled Array: " +a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Example 2:

The subsequent illustration demonstrates how to shuffle a string array in JavaScript by utilizing the random function along with the reduce method.

Example

<!DOCTYPE html>
<html>
<head>
<title> How to shuffle array using javascript </title>
</head>
<body style = "background-color:beige;">
<h3> How to shuffle array using javascript </h3>
<p> Shuffle number Array Using JavaScript random and reduce methods.
</p>
<button type = "button"
onclick = "displayData();">
Click Here to display the shuffle array. </button>
<p id = "demo" style = "color:red;"></p>
<script>
function displayData(){
// Given array
const a = ["ram", "sham", "kahna", "parth",  "karan",  "radha", "shiv"];

// Shuffle the array using reduce() and math.random() methods
const a1 = a.reduce(
    (acc, _, i) => {
        
        // Generate a random index of array
        const random = Math.floor(Math.random() * (acc.length - i)) + i;
        
        // Swap the element with the random index element of an array
        [acc[i], acc[random]] = [acc[random], acc[i]]; 
        
        return acc;
    },
    [...a] // Initialize accumulator as a shoallow copy of the array
);

// Show the shuffled array in the tab as output
console.log("Shuffled Array: "+a1);
 document.getElementById("demo").innerHTML = "Shuffled Array: "+a1;

}
</script>
</body>
</html>

Output

The output shows the shuffled array.

Challenges associated with recursion:

  • Efficiency: This method can be suboptimal since splice operates with a time complexity of O(n).
  • Stack overflow: If the array is large, there is a risk of encountering a stack overflow error due to the repeated invocation of the method through recursion.
  • Best Methods for Changing Arrays

  • Employ Fisher-Yates: It has been shown that the most effective and equitable way to shuffle an array is to use the Fisher-Yates shuffle. For the best performance and randomization, always choose this algorithm over others.
  • Exercise caution when using sort: Although it may appear straightforward to use sort with a random comparator, shuffle should generally avoid this method owing to its slowness and lack of actual randomization.
  • Think about utilizing libraries: Popular libraries like Lodash provide dependable and efficient shuffle routines if you don't want to create your shuffling logic.

The following table illustrates the time and space complexity associated with the three techniques utilized for shuffling the array.

Method Time Complexity Space Complexity
Fisher-Yates Shuffle O(n) O(1)
Sort with Random Comparator O(n log n) O(log n)
Recursive Shuffle O(n^2) O(n)

Conclusion

In numerous applications, including simulations and gaming, the process of shuffling an array is essential. The Fisher-Yates shuffle has become the gold standard for array randomization due to its efficiency and unbiased randomization. While alternative shuffling methods, such as sorting or recursive shuffling, are available, they often encounter challenges related to either accuracy or performance.

When creating a JavaScript application that requires shuffling, it is advisable to implement the Fisher-Yates algorithm. This method is not only simple and efficient but also provides unbiased randomization, as it ensures that each possible arrangement of the array is equally likely to occur.

Input Required

This code uses input(). Please provide values below: