Steven Vachon

Shuffle and Randomize Arrays in ActionScript and JavaScript

0 comments

I’d been looking around for the best solution for this and most of what I had found either performed poorly or wasn’t quite random enough. Not so strangely in the end, the best solution was the most basic.

Note: This also works fine with the ActionScript 3 Vector() class.

For ActionScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function shuffleArray(array:Array):Array
{
	for (var i:int=0, len:int=array.length; i<len; i++)
	{
		var j:int = Math.round( Math.random() * (len-1) );
 
		var value:* = array[i];
 
		array[i] = array[j];
		array[j] = value;
	}
 
	return array;
}

For JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function shuffleArray(array)
{
	for (var i=0, len=array.length; i<len; i++)
	{
		var j = Math.round( Math.random() * (len-1) );
 
		var value = array[i];
 
		array[i] = array[j];
		array[j] = value;
	}
 
	return array;
}


Comments

Top

Leave a Reply

Comments welcome! Name & email required; email always kept private. Please use basic markup. Wrap code with <code> tags.