Random Shuffle Javascript Array
Shuffle a javascript array in random order. The following three examples offer different ways to sort a Javascript array.
Examples 1, 2 and 3 are written as conventional function and as prototypes.
The functions below are all called like this:
shuffledArray = shuffle(array); // conventional functions shuffledArray = array.shuffle(); // prototype functions
Example 1:
Conventional function:
function shuffle(arr) {
return this.sort(function() { return 0.5 - Math.random(); });
}
Prototype:
Array.prototype.shuffle = function() {
return this.sort(function() { return 0.5 - Math.random(); });
}
Example 2:
Conventional function:
function shuffle(arr) {
return arr.map((a) => ({sort: Math.random(), value: a})).sort((a, b) => a.sort - b.sort).map((a) => a.value);
}
Prototype:
Array.prototype.shuffle = function() {
return this.map((a) => ({sort: Math.random(), value: a})).sort((a, b) => a.sort - b.sort).map((a) => a.value);
}
Example 3:
Conventional function:
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
Prototype:
Array.prototype.shuffle = function() {
for (var i = this.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
}