Randomising an array using Java script

SimonElliott's picture

This function can be used to randomise an existing javascript Array object.
It first creates a new array object and then iterates through each element of the old array,
randomly placing the old array elements into the new array.

function randomiseArray(arr){
 var ptr = 0;
 var newArr = new Array();
 
 while (ptr < arr.length){
  var idx =0;
  do
   idx = parseInt(arr.length * Math.random());
  while(typeof newArr[idx] != 'undefined')
  
  var element = arr[ptr++];
  newArr[idx] = element;
 } 
 return newArr;
}

This function can be very usefully randomising small arrays, performance drops off when arrays get really
large as it attempts to place each new element randomly, apart from the it works well. You are free to use
and distribute this code.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.