/ Published in: Other
Expand |
Embed | Plain Text
function randomizeArray(array:Array):Array{ var newArray:Array = new Array(); while(array.length > 0){ newArray.push(array.splice(Math.floor(Math.random()*array.length), 1)); } return newArray; }
Comments
Subscribe to comments
You need to login to post a comment.

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: