Saturday, 7 June 2008

Randomising an array using Java script

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;
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.

No comments:

Elliott - a little more

London, United Kingdom
I am an architect with shed loads of familiarity in providing high profile consumer media, products and services. I conceive ideas, design and lead projects to create new consumer products. I love brainstorming ideas with marketing counterparts and creating future facing and innovative solutions. I have been responsible for high volume mass consumer market features where scale, reliability and the ability to quickly respond are of crucial importance.