How to shuffle elements of an Array in JavaScript

In this tute, we will discuss how to shuffle elements of an array in JavaScript. Before getting into the topic, let’s see what is an array.

An array is a special variable that can contain more than one value. These elements can be of the same or different data types. Few examples of arrays are,

// Arrays of single type of elements
var arr1 = [7, 17, 10];
var arr2 = ['k', '2', 'hola'];
var arr3 = [55.3, 10.45];

// Array with multiple types of elements
var arr4 = [17, 'foo', 55.99];

Shuffle elements of an Array:

There are many ways to shuffle elements of an array in JavaScript. Let’s see two commonly used methods in here.

Method 1:

In this method, we will define a new function called shuffle(). This function will use Math.random() function to get random index and swap those elements to shuffle randomly.

Algorithm:

  1. Firstly, iterate through all the indices in the array.
  2. At each index, generate a random index to swap with by using Math.random() method.
  3. To swap the elements at indices i and j, create a new variable temp and store the value at arr[j] in this.
  4. Save the arr[i] value in arr[j].
  5. Save the temp value in arr[i].
  6. Return the shuffled array.

Pseudocode:

function shuffle(arr):
    for i in [0, n-1]:
        j = getRandomInt(n)
        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
    return arr

Code Snippet:

function shuffle(arr) {
  var n = arr.length;              // Length of the array
  
  for(var i=0 ; i<n-1 ; ++i) {
    var j = getRandomInt(n);       // Get random of [0, n-1]
    
    var temp = arr[i];             // Swap arr[i] and arr[j]
    arr[i] = arr[j];
    arr[j] = temp;
  }
  
  return arr;                     // Return shuffled array
}

var arr = [1, 2, 3, 4, 5, 6, 7];

arr = shuffle(arr);

console.log(arr);

 Output:

7,5,3,6,2,1,4

Method 2:

In this method, we will make use of methods like sort(), Math.random(). The algorithm used to shuffle elements is:

Algorithm:

  1. Call the sort() method on the array.
  2. In the sort() method, define a function which returns value in the range [-0.5, 0.5].

Pseudocode:

function shuffle(arr):
    for i in [0, n-1]:
        j = getRandomInt(n)
        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
    return arr

Code Snippet:

function shuffle(arr) {
  var n = arr.length;              // Length of the array
  
  for(var i=0 ; i<n-1 ; ++i) {
    var j = getRandomInt(n);       // Get random of [0, n-1]
    
    var temp = arr[i];             // Swap arr[i] and arr[j]
    arr[i] = arr[j];
    arr[j] = temp;
  }
  
  return arr;                     // Return shuffled array
}

var arr = [1, 2, 3, 4, 5, 6, 7];

arr = shuffle(arr);

console.log(arr);

 Output:

7,5,3,6,2,1,4

 

Leave a Reply

Your email address will not be published. Required fields are marked *