Erik’s Brain

The reward of a thing well done...

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:

// 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!

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.