Implementing Array.shuffle() in Actionscript

One useful thing that Actionscript doesn’t offers is the ability to shuffle an array, however this can be accomplished in a blink of an eye and with very few lines of code. Before to implement my own solution, I looked on the web, but solutions provided by others developers looks too complex and too long to type. What I found was based on a for loop and several line of codes to fill a secondary array with the elements in a new random order. My solution instead is based on a while loop (3 lines of code only):

var arr2:Array = [];
while (arr.length > 0) {
    arr2.push(arr.splice(Math.round(Math.random() * (arr.length - 1)), 1)[0]);
}

How it works?

First we have to create a new array (arr2) which will contains the elements from the base ordered array (arr), then we use a while loop, which can be translated into english as: “do this until base array is not empty”. Inside the loop, we push into the second array a random element from the first array and, at the same time, we remove that element from its array. Array’s method splice() in fact, removes one or more elements from an array and returns an array containing the deleted elements, that in our case is only one (as specified in the second argument). The first argument of the method represent the starting index from which to start to delete, this is dynamically calculated by using the Math.random() method (which returns a number between 0 and 1), then multiplied by the length of the base array minus 1, because array length is always 1 greater than elements array contains (cause array indexing starts from zero), finally this number is rounded to the nearest integer by Math.round(), in order to access an exact index.

I think this is the best and shorter way to implement a shuffle functionality :)