I have rarely wanted to randomize an array with Javascript; however, whenever I do I forget how to do it. Today that day changes, I’m going to write it down to both help my memory as well as have an easy place to find it in the future. Alright, let’s look at a simple solution to randomizing or shuffling a Javascript array.
[code]
var arr1 = [“a”, “b”, “c”, “d”];
arr1.sort(() => (Math.random() > .5) ? 1 : -1);
console.log(arr1);
[/code]
The concept behind this is, typically sort could be used to sort alphabetically or numerically, instead a random number is generated between 0 and 1 using Math.random. For each element in that array, if the random value is less than 0.5 it will put a 1 and vice-versa put a -1 to randomly decide the sort order.
As always, I like to extend this as an Array prototype function:
[code]
var arr1 = [“a”, “b”, “c”, “d”];
Array.prototype.shuffle = function() {
return this.sort(() => (Math.random() > .5) ? 1 : -1);
}
console.log(arr1.shuffle());
[/code]
And voila a simple yet effective way to randomly sort an array using Javascript.