Javascript Array has loads of useful function, but still there are some function that I wish were there. One of those function is shuffling an array, rearrange it’s components order in random sequence.

Ruby have its Array#shuffle and Array#shuffle! to shuffle an array. Altough Javascript doesn’t have a native method to do the same, we can easily create our own array shuffling method, courtesy of CSS-Tricks.

1
2
3
4
5
6
7
8
[1, 2, 3, 4, 5].sort(function() { return 0.5 - Math.random() });

// or to extend its prototype
Array.prototype.shuffle = function() {
return this.sort(function() { return 0.5 - Math.random() });
}

[1, 2, 3, 4, 5].shuffle(); // => [3, 1, 4, 2, 5]

So, there you have it, a function to shuffle an array in javascript. I find this function quite useful for one of my pet project, I hope this is usefull for you too.