How to shuffle an array in JavaScript

OpenJavaScript 0
Reading Time: < 1 minute 🕑

Last updated: September 27, 2022.

JavaScript does not provide a native function or method for shuffling elements within an array.

But you can create this functionality to call upon by creating a utility function.

Below is the code for such a function: it accepts an array and returns an array of the same length containing the contents of the passed in array in a random order.

/* An array shuffling utility function */

// The function
function shuffle(array) {
  let shuffledArray = [];
  let usedIndexes = [];

  let i = 0;
  while (i < array.length) {
    let randomNumber = Math.floor(Math.random() * array.length);
      if (!usedIndexes.includes(randomNumber)) {
        shuffledArray.push(array[randomNumber]);
        usedIndexes.push(randomNumber);
        i++;
        }
    }
    return shuffledArray;
}

// Usage
const myArray = ['Freddie', 'Brian', 'Roger', 'John'];
shuffle(myArray); // e.g. ['Roger', 'Freddie', 'John', 'Brian'];

The logic of the function is to push array elements from a passed in array to a new array based upon a random index value corresponding to an index value of the passed in array. The random value is generated by Math.random().

Each time a random index value is used to push an element from the passed in array to the new one, it is saved in usedIndexes. Then, when a new random index is generated, usedIndexes is checked to see if it already contains the index value. If it does, this value is not used to push a value from the passed in to new array.

The while loop that executes this iterative process continues until all index values for the passed in array have been pushed into the new array.