Randomise JavaScript Array

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.

function fisherYates(myArray){
 var i = myArray.length;
 if(i == 0){
  return false;
 }
 while(--i){
  var j = Math.floor(Math.random() * (i + 1));
  var tempi = myArray[i];
  var tempj = myArray[j];
  myArray[i] = tempj;
  myArray[j] = tempi;
 }
 return myArray;
}

Use the function in the following manner.

var numbers = new Array(1,2,3,4,5,6,7,8,9);
alert(numbers);
numbers= fisherYates(numbers);
alert(numbers);

 

Comments

Permalink

I am sorry. My English is just a little. I hope that you can understand me.

I tested fisherYates function.

fisherYates function is no good.

The Better Ways is blelow method.

OneArray.sort(function(){return Math.random() - Math.random();});

This sort function is more equitable !

var OneArray=[1,2,3,4,5,6,7,8,9,0];

Result 1, 2

OneArray.sort(function(){return Math.random() - Math.random();});

(1061) 0
(1003) 1
(990) 2
(964) 3
(1025) 4
(1010) 5
(970) 6
(996) 7
(1029) 8
(952) 9

(989) 0
(1029) 1
(1021) 2
(983) 3
(981) 4
(1004) 5
(948) 6
(963) 7
(1023) 8
(1059) 9
-------------

fisher Yate funcion test

(1007) 0
(1048) 1
(992) 2
(1026) 3
(1004) 4
(981) 5
(950) 6
(1052) 7
(1000) 8
(940) 9

(1025) 0
(1027) 1
(965) 2
(990) 3
(984) 4
(1042) 5
(997) 6
(1024) 7
(953) 8
(993) 9

(1014) 0
(1014) 1
(984) 2
(1058) 3
(979) 4
(996) 5
(1014) 6
(978) 7
(977) 8
(986) 9


Anonymous (Sun, 06/12/2011 - 03:26)

Permalink

Wow! Thanks! I really appreciate you taking the time to post a comment giving such a detailed analysis. 

If you feel like it, maybe you could write some other comments? Or even an full article? :)

Add new comment

The content of this field is kept private and will not be shown publicly.