Quick Tip #1 – Randomize an ActionScript 3 Array

Okay, finally getting down to what I wanted to do when I jumped into WordPress this morning!

I’ve often wanted to randomize an Array. You know, take an Array and shuffle it up. Maybe I’ve got a list of images to show in a slideshow but don’t want to show them in order. Whatever… there are tons of reasons to mix up an array.

Here’s the code to do it:

1
2
3
4
5
6
7
8
9
10
11
// create the Array
var a:Array = [1,2,3,4,5,6,7,8,9,0]
 
// create a comparison function that will be passed
// to the Array.sort() method
function randomSort(objA:Object, objB:Object):int {
	return Math.round(Math.random() * 2) - 1
}
 
// randomize the Array!
a.sort(randomSort);

Basically, the Array.sort method compares two elements at a time to determine which should be first, objA or objB. In this example, the sort() method uses the function that’s passed in as its sole argument. In this case our sorting function doesn’t actually have any logic built into it to compare the elements. It simply returns either -1, 0, or 1. Taken from the official ActionScript 3 reference:

A comparison function used to determine the sorting order of elements in an array. This argument is optional. A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:

  • A negative return value specifies that A appears before B in the sorted sequence.
  • A return value of 0 specifies that A and B have the same sort order.
  • A positive return value specifies that A appears after B in the sorted sequence.
This entry was posted in ActionScript. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Tony
    Posted November 17, 2009 at 10:35 pm | Permalink

    Dudes, your hard effort has saved me a lot of time and hair-pulling for this urgent assignment i need to get done in like 1 day!!!

    THANKS MAN!! God bless you!! :D

  2. I
    Posted January 1, 2010 at 5:24 am | Permalink

    Works great!

  3. Jose
    Posted June 3, 2010 at 9:52 pm | Permalink

    the shuffling is not happening properly

    3 9 1 4 5 6 7 8 2 0

    3 2 5 4 6 1 7 8 9 0

    • Posted June 6, 2010 at 12:09 pm | Permalink

      Sometimes random isn’t as random as you want it to be. Those results look pretty typical to me.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • Categories