I want to shuffle the questions in my quiz. I figured out one way to shuffle the questions object and found a function to shuffle an array on SO. I’ve put it all together and it all works but looks rather cumbersome. Is there a better, more elegant way?
function knuthShuffle(arr) {
var rand, temp, i;
for (i = arr.length - 1; i > 0; i -= 1) {
rand = Math.floor((i + 1) * Math.random());//get random between zero and i (inclusive)
temp = arr[rand];//swap i and the zero-indexed number
arr[rand] = arr[i];
arr[i] = temp;
}
return arr;
}
Array.sort() accepts any number, not just 1 & -1. Besides that the shown function returns either 0.5 or -0.5, so shuffling is achieved.
The reason for the preference of the Knuth shuffle is IMO the better randomness, since it does not depend on any of the values to shuffle (unlike the sort shuffle).