Randomize an Array

Submitted by:Jhon Jhon

Date added:18 May, 2011

Category:ActionScript

To randomize an array we loop over the length of the array, removing an object chosen at random and then adding it back onto the Array’s end position. Think of this as having a deck of cards where you pick a card at random from the deck and move it to the top of the stack repeated for the total number of cards in the deck.

It’s important to note that the splice method returns an Array containing the removed object and not the object itself hence adding the [0] after the splice call to reference the contained object.

Tags: randomize array

Code Snippet:

    for (var i:uint = 0; i < myArray.length; i++)
{
var rand:uint = int(Math.random() * myArray.length);
myArray.push( myArray.splice( rand, 1 )[0] );
}
 
 

Comments