Shuffling the order of an array with Javascript

javascript

In this post, I’ll show you how to shuffle the order of an array in Javascript.

For this example, we will need an array of string values, something like this:

var greeknumbers = new Array();
greeknumbers[0] = "alpha";
greeknumbers[1] = "beta";
greeknumbers[2] = "gamma";
greeknumbers[3] = "delta";
greeknumbers[4] = "epsilon";
greeknumbers[5] = "zeta";
greeknumbers[6] = "omega";
greeknumbers[7] = "sigma";
greeknumbers[8] = "psi";
greeknumbers[9] = "chi";

Next, we will need the following Array.prototype constructor.

Array.prototype.shuffle = function() {
	var len = this.length;
	for (var i = 0; i<len; i++) {
		var rand = Math.floor(Math.random()*len);
		//swap current index with a random one
		var temp = this[i];
		this[i] = this[rand];
		this[rand] = temp;
	}
};

(You can learn more about these at this link on developer.mozilla.org)

If we were to log this array to the console we would see this:

["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "omega", "sigma", "psi", "chi"]

This is listing out the array in it’s initial order.

To shuffle the order of this array, we run the shullfe Array.prototype on our array like this:

greeknumbers.shuffle();

This function returns nothing, but it re-arranges the order of the array. So if we now log the array to the console, we would see something like this:

["delta", "chi", "beta", "gamma", "sigma", "psi", "alpha", "zeta", "epsilon", "omega"]

The arrays order has been re-sorted or shuffled in a random order!

So what is this actually doing? Lets work it out, step by step.

First, we create our Array.prototype constructor:

Array.prototype.shuffle = function() {
};

Next, we create a variable to store the length of the array.

Array.prototype.shuffle = function() {
	var len = this.length;
};

Then, we create a loop over the arrays length

Array.prototype.shuffle = function() {
	var len = this.length;
	for (var i = 0; i<len; i++) {		
	}
};

Then, inside this loop, we create a variable to store a random number according to the the arrays length

Array.prototype.shuffle = function() {
	var len = this.length;
	for (var i = 0; i<len; i++) {
		var rand = Math.floor(Math.random()*len);		
	}
};

To explain what this on line is doing, I will start from the inner-most statements. Math.random() will generate a random number, as developers.mozilla.org puts it:

The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Source https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random.

Then we multiply the returned random number by the length of the array, this is to ensure that we get a number within the range of our arrays length.

Math.random will return a floating point number, which we don’t want, so we wrap that in a Math.floor call, which will return an integer.

If we were to log tihs the console, our code at this point would return something like the following:

9
0
3
6
5
9
5
2
6
2

OK, so the next thing we do, is to swap the items in the array with the random number we have found in the previous line.

Array.prototype.shuffle = function() {
	var len = this.length;
	for (var i = 0; i<len; i++) {
		var rand = Math.floor(Math.random()*len);
		//swap current index with a random one
		var temp = this[i];
		this[i] = this[rand];
		this[rand] = temp;
	}
};

And that’s it! If you found this code useful, please leave a comment!