Monday, August 29, 2011

JavaScript Array Scrambling

Ever need to randomly re-order an array in JavaScript? I have. And, unfortunately, there is no native support for a function like shuffle() in PHP.

I found a few people suggest this technique, but I have found it to not be very good. The elements weren't all that random especially for the first and last elements in particular (they were usually one of two values).

myArray.sort( function(a, b) {
return Math.round((Math.random() * 100) - 50);
});

It uses the native sort() function requires a function that will compare two values to determine which one comes first. If the number returned is negative it indicates that the 'a' item goes first and vice-versa if it is positive.

I found the following function to be more random:

function mixArray(arrayIn) {
var arrayOut = [];
var origLength = arrayIn.length;
for (var x = 0; x < origLength; x++) {
var randIndex = Math.floor(Math.random() * arrayIn.length);
if (randIndex == arrayIn.length) randIndex--;
arrayOut.push(arrayIn.splice(randIndex, 1)[0]);
}
return arrayOut;
};
myArray = mixArray(myArray);

No comments: