Javascript Array shuffle
Oct 8, 2014
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 | [1, 2, 3, 4, 5].sort(function() { return 0.5 - Math.random() }); |
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.