RSS
2 Dec 2008

Javascript array shuffle function

Author: Richard Francis | Filed under: Web Development

I was recently trying to solve a problem for a colleague of mine. He wanted to simply shuffle an array. I hunted around for hours trying to find a way to do this. Eventually I found an algorithm and built this into an easy to use function.

You simply parse the array that you wish to shuffle, and the function will return a new (shuffled) array. The code is as follows:

function shuffle(theArray){
    for (var j, x, i = theArray.length; i; j = parseInt(Math.random() * i), x = theArray[ i], theArray[i] = theArray[j], theArray[j] = x);
    return theArray;
};

I hope you find this useful!

If you like this post, why not bookmark it?
  • Digg
  • StumbleUpon
  • del.icio.us
  • Reddit
  • MySpace
  • Facebook
  • Google
  • Live
  • Technorati
  • Sphinn
  • Mixx
  • E-mail this story to a friend!

Tags: ,

4 Responses to “Javascript array shuffle function”

  1. James Degget says:
  2. Cool!

  3. This is a useful function, and it’s hard to find too!

    Thanks

  4. Why can’t I see the code? Are you able to post again?

  5. Sorry about that Chantal! You should be able to see the code now.

    All the best
    Richard

Leave a Reply