Wwwebber's Blog

Randomize Elements in an Array

Posted in actionscript 3, array by wwwebber on November 28, 2008

I had to rewrite some code that randomized elements in the new Vector class (had written the code below to randomize array elements)and thought I’d post both the old array randomizer() here. nothing fancy at all…just thought might be useful to someone.

var myArray:Array =[1,2,3,4,5,6];

function randomize(arr:Array):Array{
var originalA:Array = arr;
var newA:Array=[];

while(originalA.length > 0){
var index:int = int(Math.random() * originalA.length);
var element = originalA.splice(index,1);
//splice returns an array.


return newA;



Note: the splice() method of the array class actually returns an Array made up of the elements you’ve spliced out of the original array. This is why we need to push element[0] into the new randomized array.

Comments Off on Randomize Elements in an Array