It's never to late (shuffle AS function + more)

My statistics show how search array AS functions post is very popular, even two and a half years old! I also see how I never answered Lance to his comment how shuffle function works. So, Lance, two and a half years later here it is.

How does shuffle function works?

We have two arrays, starting array 'before' (b) and final array 'after' (temp). In every while step we have next process:

1 - first we take randomly chosen element from first array,
2 - than we push that element into new array temp
3- and finally with splice we remove that element from first array, which reduces its length. Iteration works while there are element inside 'before' array. OK?


before = [3, 65, 202, -4];
after = shuffle(before);

Variable templen doesn't have to be Number. If you change type to Object, function will work with Strings, arrays within arrays, Objects.

example 2:

before = [3, "hello", [4, 7, 9], -8];
after = shuffleB(before);

Here is one more ActionScript search arrays function. This one takes two arrays and returns difference array, meaning it deletes all elements of second function which appear inside first function:

function difference(a:Array, b:Array):Array{
var bCounter = b.length-1;
while(bCounter >= 0) {
var aCounter = a.length-1;
while(aCounter >=0) {
if(a[aCounter]==b[bCounter]) {
a.splice(aCounter, 1);
aCounter -= 1;
bCounter -= 1;
return a;

example 3:

a1 = [3, 5, 7, 9, 3];
a2 = [3];
a3 = difference(a1, a2);

To be continued ...


Post a Comment


  1. This seems to be a GREAT POST.

    In laymens terms, how might you describe the integration process for people who are relatively new to flash.

    I've come across many great tutorials, however, yours seems to be the easiest, and most non-complex to understand.

    How would I go about "shuffle" once the media player is already loaded and I click the next button.

    Below you will see my function playTrack and function nextTrack.

    Could I add a chunk of code with-in these functions to enable a "shuffle" feature.

    function playTrack(e:MouseEvent):void {
    if (!trackOn) {
    newUrlRequest = new URLRequest(trackXML.track[index].path);
    newTrack = new Sound(newUrlRequest);
    chan =;
    play_mc.removeEventListener(MouseEvent.CLICK, playTrack);
    trackOn = true;
    title_txt.text = trackList[index].title;
    performer_txt.text = trackList[index].performer;


    function nextTrack(e:MouseEvent):void {
    if (index < trackList.length() - 1) {
    index = 0;
    newUrlRequest = new URLRequest(trackList[index].path);
    newTrack = new Sound(newUrlRequest);
    chan =;
    play_mc.removeEventListener(MouseEvent.CLICK, playTrack);
    trackOn = true;
    track = newTrack;
    title_txt.text = trackList[index].title;
    performer_txt.text = trackList[index].performer;

    I'll go ahead and bookmark this post, again, Thanks a bunch for the help.


Thanks for sharing your thoughts !