Learn how to shuffle an array in javascript

An algorithm to shuffle a given array in javascript.

While many programming languages like PHP and Ruby have inbuilt methods to shuffle the array, javascript does not.

So we are going to implement our own function to shuffle the array.

Example

Input:
[2, 5, 7, 11, 25]

Output:
[2, 25, 7, 11, 5]

We are going to use Fisher–Yates shuffle algorithm to shuffle the array.

The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence—in plain terms, the algorithm shuffles the sequence. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain.

Basically what it does is, it loops till then given length of the array and in each iteration it generates random index (bounded to the array length) and swap the elements at that place.

Implementation for an algorithm to shuffle array in javascript.

let shuffle = (arr, currentIndex = arr.length) => {
  
  while(currentIndex !== 0){
    //Get a random index
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    
    //Swap the values
    let temporaryValue = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = temporaryValue;
  }
  
  return arr;
}
Input:
let arr = [2, 5, 7, 11, 25];
console.log(shuffle(arr));

Output:
[7, 11, 5, 2, 25]

This method shuffles the array in place, if you want a new copy then just pass a copy for shuffling by using arr.slice().

Input:
let arr = [2, 5, 7, 11, 25];
console.log("Original Array", arr);
console.log("Shuffled array", shuffle(arr.slice()));

Output:
"Original Array" [2, 5, 7, 11, 25]
"Shuffled array" [11, 25, 5, 2, 7]

We can also add a method to the prototype of the array to use it universally.

Array.prototype.Shuffle = function(){
  let arr = this.slice();
  let currentIndex = this.length;
  
  while(currentIndex !== 0){
    //Get a random index
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    
    //Swap the values
    let temporaryValue = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = temporaryValue;
  }
  
  return arr;
}
Input:
let arr = [2, 5, 7, 11, 25];
console.log(arr.Shuffle());

Output:
[5, 7, 2, 25, 11]

This method will always return a new shuffled array, It will not mutate the original array.