javascript tutorial - [Solved-5 Solutions] How to randomize a javascript array ? - javascript - java script - javascript array
Problem:
We have an array like this:
var arr1 = ["a", "b", "c", "d"];
click below button to copy the code. By JavaScript tutorial team
How can WE randomize / shuffle it ?
Solution 1:
The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Used like so
var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);
click below button to copy the code. By JavaScript tutorial team
Solution 2:
[community edit: This answer is incorrect; see comments. It is being left here for future reference because the idea is not that rare.]
[1,2,3,4,5,6].sort(function() {
return .5 - Math.random();
});
click below button to copy the code. By JavaScript tutorial team
Solution 3:
One could (or should) use it as a protoype from Array: From ChristopheD:
Array.prototype.shuffle = function() {
var we = this.length, j, temp;
if ( we == 0 ) return this;
while ( --we ) {
j = Math.floor( Math.random() * ( we + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
}
click below button to copy the code. By JavaScript tutorial team
Solution 4:
Use the underscore.js library. The method _.shuffle() is nice for this case. Here is an example with the method:
var _ = require("underscore");
var arr = [1,2,3,4,5,6];
// Testing _.shuffle
var testShuffle = function () {
var indexOne = 0;
var stObj = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5
};
for (var we = 0; we < 1000; i++) {
arr = _.shuffle(arr);
indexOne = _.indexOf(arr, 1);
stObj[indexOne] ++;
}
console.log(stObj);
};
testShuffle();
click below button to copy the code. By JavaScript tutorial team
Solution 5:
Adding to @Laurens Holsts answer. This is 50% compressed.
function shuffleArray(d) {
for (var c = d.length - 1; c > 0; c--) {
var b = Math.floor(Math.random() * (c + 1));
var a = d[c];
d[c] = d[b];
d[b] = a;
}
return d
};