4th July 2008 - 3 minutes read time
Randomising a JavaScript array can be done in one or two ways. The easy way is to create a function that returns a random number and then use the sort() function of the Array object to sort the array by a random value.
// random number
function randNumber(){
return (Math.round(Math.random())-0.5);
}
// create array
var numbers = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// print array
alert(numbers);
//randomise array
numbers.sort(randNumber);
//print random array
alert(numbers);
The sort function works by taking the randNumber function as a parameter. For every item of the array it uses this function to compare one value to the next. If the function returns a random number then the array will be sorted randomly.
The second method is slightly more complex and involves using the Fisher Yates randomising algorithm. The following function takes in an array and returns a randomly sorted array.