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!
Tags: Algorithms, Javascript
































Cool!
This is a useful function, and it’s hard to find too!
Thanks
Why can’t I see the code? Are you able to post again?
Sorry about that Chantal! You should be able to see the code now.
All the best
Richard