Posted By

Wiederkehr on 01/19/09


Tagged

textmate random array as3


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

tbass134
noone453
adrianparr
IsoJon
tspitzr
mitien
alsodenn
fjckls
Oussama


AS3 randomize array


 / Published in: Other
 

  1. function randomizeArray(array:Array):Array{
  2. var newArray:Array = new Array();
  3. while(array.length > 0){
  4. newArray.push(array.splice(Math.floor(Math.random()*array.length), 1));
  5. }
  6. return newArray;
  7. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jusksmit on April 26, 2010

I've actually been using this snippet for a long time, but I just stumbled across a small problem. Fortunaately, there is an easy solution, and I figured I'd share it here.

When you call array.splice(), it always returns an array - even if you are only splicing out one object, like in this snippet. That means that we're technically pushing single-element arrays into "newArray", instead of the actual objects.

Now, when you are just dealing with arrays of strings, numbers, or other simple data, this isn't an issue, because everything will be automatically translated from a single-element array into a single object, but if you are shuffling an array of complex Objects with their own children and properties, you will run into problems with properties getting lost in translation.

The simple fix? Instead of pushing the result of the splice directly, push the first index of the result. The updated code looks like this:

    function randomizeArray(array:Array):Array {
        var newArray:Array = new Array();
        while(array.length > 0){
            var obj:Array = array.splice(Math.floor(Math.random()*array.length), 1);
            newArray.push(obj[0]);
        }
        return newArray;
    }

You need to login to post a comment.