CancelImage Upload

How to shuffle an array in JavaScript

You would think JavaScript would already have a pre-built in shuffle function. Something along the lines of the PHP function shuffle(). Well, unfortunately JavaScript does not posses such a function. Meaning it is up to us as programmers to create it ourselves.

To accomplish this task we will require a function that that takes an array, exchanges its individual elements (which is the essence of a shuffle), and then returns it in its new order. Here then is an example of how this can be accomplished:

<html>
<head>
<title>How to shuffle an array in JavaScript</title>
<script language="JavaScript">

Array.prototype.shuffle = shuffle;

function shuffle()
{

      var tempSlot;

      var randomNumber;

      for(var i =0; i != this.length; i++)
      {

            randomNumber = Math.floor(Math.random() * this.length);

            tempSlot = this[i];

            this[i] = this[randomNumber];

            this[randomNumber] = tempSlot;

      }

}

function shuffleNumbers()
{

      var numbers = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

      numbers.shuffle();

      var numbersAfterShuffle = numbers.join("<br>");

      document.getElementById("result").innerHTML = numbersAfterShuffle;

}

</script>
</head>
<body onload="javascript:shuffleNumbers();">

<span id="result"></span>

</body>
</html>

The key to this code of course is the function shuffle, where the individual array elements are exchanged:

function shuffle()
{

      var tempSlot;

      var randomNumber;

      for(var i =0; i != this.length; i++)
      {

            randomNumber = Math.floor(Math.random() * this.length);

            tempSlot = this[i];

            this[i] = this[randomNumber];

            this[randomNumber] = tempSlot;

      }

}

These are passed on to shuffle, by the following code:

Array.prototype.shuffle = shuffle;

function shuffleNumbers()
{

      var numbers = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

      numbers.shuffle();

      var numbersAfterShuffle = numbers.join("<br>");

      document.getElementById("result").innerHTML = numbersAfterShuffle;

}

And as you can see the end result will be passed to the span with the id result via getElementById(). Not quite as straight forward as simply calling on a function named shuffle(), as in most programming languages. But at least you only have to define this code once!

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com