Home » Programming » Javascript » Javascript Randomize Shuffle Array

How to Randomize/Shuffle an Array in JavaScript [Examples]

This article will show you a few ways, both easy and complex, to randomize/shuffle an array in JavaScript.

The Quick and Dirty Way to Randomize an Array

If you aren’t too concerned about the probabilities involved, this code is a quick way to randomize the contents of an array:

// Function to return a shuffled copy of a given array
function shuffle(array) {
    var shuffled = [...array]; // Make a copy of the array to be shuffled so that the original is not altered by the sort() function below
    shuffled.sort(() => Math.random() - 0.5); // Sort the array using the sort() method with random input from Math.random()
    return shuffled; // Return the shuffled copy of the array
}

It is used like so:

var fruitArray = ['peach', 'apple', 'banana', 'pear']; // Create an array of fruit
shuffledFruit = shuffle(fruitArray); // Shuffle it and assign the returned value to a new variable
console.log(shuffledFruit); // Will print the shuffled copy of the array

This method, however, is not truly random – it’s a weakness in the sort() method as implemented in JavaScript. The Math.random() function is also not entirely random.

This method, however, is good enough for basic scenarios where you don’t care too much about efficiency or randomness, like randomizing the seating order for students in a class or the colors of players in a game. On the other hand, if you’re writing a lottery program or are working in some other scenario where the probabilities and fairness matter, you will want to use a different method.

The Modern Fisher-Yates Shuffle in JavaScript (The Right Way)

The Fisher-Yates is a method of randomizing/shuffling a sequence of items that is truly random. It’s the best way of doing it, but it requires a bit of extra coding as JavaScript has no built-in implementation.

As for why it’s better? I recommend checking out the Wikipedia article for a proper explanation. But, I’ll stick to the code:

// Function to return a shuffled copy of a given array (Fisher-Yates)
function shuffle(array) {
    var shuffled = [...array]; // Make a copy of the array to be shuffled so the original is not altered
    for (var i = shuffled.length - 1; i > 0; i--) { // Loop through each index (position) in the array
        var j = Math.floor(Math.random() * (i + 1)); // Pick an index randomly from the array
        var temp = shuffled[i]; // Store the value at the current index
        shuffled[i] = shuffled[j]; // Replace the value at the current position with the one at the randomly picked index
        shuffled[j] = temp; // Replace the value at the randomly picked index with the one which was at the current index (swapping them!)
    }
    return shuffled; // Return the shuffled array
}

It is used the same way as the previous example:

var fruitArray = ['peach', 'apple', 'banana', 'pear']; // Create an array of fruit
shuffledFruit = shuffle(fruitArray); // Shuffle it and assign the returned value to a new variable
console.log(shuffledFruit); // Will print the shuffled copy of the array

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment