To shuffle(randomize) an array in javascript, there is an algorithm called Fisher-Yates devised and Don Knuth popularized algorithm.
Below is the code for using it:-
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var valueAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = valueAtIndex;
}
return input;
}
var tempArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
tempArr.shuffle();
// and the result is...
alert(tempArr);
The function shuffle is used as prototype,so it is used in the array object as shown above. In this code this keyword is used for reference the array object inside this function. Here you go through every item in the array and swap it with the random number. The i variable refers to the selected item position.
var randomIndex = Math.floor(Math.random()*(i+1));
The above line is used to extract the position of the random number. Once you have your random item position, you can get that item's contents by simply referring to it in your array:
var valueAtIndex = input[randomIndex];
Now the last thing is to swap the items.
input[randomIndex] = input[i];
input[i] = valueAtIndex;
This is how you can shuffle your array with the help of this algorithm.
0 Comment(s)