Wednesday, September 3, 2025
HomeLanguagesJavascriptHow to shuffle an array using JavaScript ?

How to shuffle an array using JavaScript ?

Shuffling an array or a list means that we randomly re-arranging the content of that structure. To shuffle an array we will use the following algorithms:

Approach: In this approach, we are using the array elements in reverse order and then swapping each element with a random one.

function shuffleArray(array) {
   for (var i = array.length - 1; i > 0; i--) { 
  
       // Generate random number 
       var j = Math.floor(Math.random() * (i + 1));
                  
       var temp = array[i];
       array[i] = array[j];
       array[j] = temp;
   }
      
   return array;
}

Example: In this example, we are using the above approach.

html




<p>Array is=[1, 2, 3, 4, 5, 6, 7]</p>
<button onclick="show()">
    click
</button>
 
<script>
    // Function to shuffle the array content
    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
 
            // Generate random number
            var j = Math.floor(Math.random() * (i + 1));
 
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
 
        return array;
    }
 
    // Function to show the result
    function show() {
        var arr = [1, 2, 3, 4, 5, 6, 7]
        var arr1 = shuffleArray(arr)
 
        document.write("After shuffling: ", arr1)
    }
</script>


Output:  

How to shuffle an array using JavaScript ?

How to shuffle an array using JavaScript ?

Approach 2: Passing a function that returns (random value – 0.5 ) as a comparator to sort function, so as to sort elements on a random basis. 

function shuffleArray(array) { 
   return array.sort( ()=>Math.random()-0.5 );
} 

Example: This example shows the use of the above-explained approach.

HTML




<p>Array is=[1, 2, 3, 4, 5, 6, 7]</p>
<button onclick="show()">
    click
</button>
<script>
    // Function to shuffle the array content
    function shuffleArray(array) {
        return array.sort(() => Math.random() - 0.5);
    }
 
    // Function to show the result
    function show() {
        var arr = [1, 2, 3, 4, 5, 6, 7]
        var arr1 = shuffleArray(arr)
 
        document.write("After shuffling: ", arr1)
    }
</script>


Output:

How to shuffle an array using JavaScript ?

How to shuffle an array using JavaScript ?

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11854 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS