A few months ago, I posted about how the classic method most JS programmers would use to randomise an array completely fails. I proposed a quick solution to it, but that solution had flaws of its own.
So, for those of you who need to shuffle decks of cards, scramble virtual eggs or just want to toss a little confusion into your applications, here’s a fully working array randomiser:
Array.randomiseArray = function(arr){
var i, v;
for (i=0; i<arr.length; i++) {
v = arr[i];
arr[i] = {
v: v,
sort: Math.random()
};
}
arr.sort(function(a, b){
return a.sort - b.sort;
});
for (i=0; i<arr.length; i++) {
arr[i] = arr[i].v;
}
return arr;
};
Pingback: An Array of Random Thoughts | Doc Emmett Splendid's