Shuffling an object

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?

This is my code

https://codepen.io/gandalf458/pen/KBWbLx

arr.sort(function () {
    return Math.round(Math.random()) - 0.5
})

Although I’m not sure how good the randomness is.

1 Like

The randomness will be . . .okay? A problem is that you’re only getting values from 0 to 1, when -1 really is wanted too by the sort method.

The Knuth shuffle is the most widely accepted way to shuffle, which can be found in several variations at http://rosettacode.org/wiki/Knuth_shuffle#JavaScript

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;
}
1 Like

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).

1 Like

Thanks guys. I think a vague sort of randomness will do for this purpose, though I have bookmarked the Knuth shuffle for future use.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.