23

I need to implement a randomization from JSON result.

The format of the JSON is two objects:

result:

Question(object)

[Object { id="4c6e9a41470b19_96235904",  more...}, 
 Object { id="4c784e6e928868_58699409",  more...}, 
 Object { id="4c6ecd074662c5_02703822",  more...}, 6 more...]

Topic(object)

[Object { id="3jhf3533279827_23424234",  more...}, 
 Object { id="4634663466cvv5_43235236",  more...}, 
 Object { id="47hf3892735298_08476548",  more...}, 2 more...]

I want to randomize the order of the objects inside the question object and the topic objects.

easement
  • 6,119
  • 3
  • 29
  • 36

3 Answers3

38

You could use a Fisher-Yates-Durstenfeld shuffle:

var shuffledQuestionArray = shuffle(yourQuestionArray);
var shuffledTopicArray = shuffle(yourTopicArray);

// ...

function shuffle(sourceArray) {
    for (var i = 0; i < sourceArray.length - 1; i++) {
        var j = i + Math.floor(Math.random() * (sourceArray.length - i));

        var temp = sourceArray[j];
        sourceArray[j] = sourceArray[i];
        sourceArray[i] = temp;
    }
    return sourceArray;
}
Guy
  • 10,931
  • 5
  • 36
  • 47
LukeH
  • 263,068
  • 57
  • 365
  • 409
13

Easiest method (not perfect shuffle, but in some cases may be better):

function randomize(a, b) {
    return Math.random() - 0.5;
}

yourQuestionArray.sort(randomize);
yourTopicArray.sort(randomize);

or

yourQuestionArray.sort(function (a, b) {return Math.random() - 0.5;});
yourTopicArray.sort(function (a, b) {return Math.random() - 0.5;});

( http://jsfiddle.net/dJVHs/ )

pepkin88
  • 2,742
  • 20
  • 19
  • 2
    For larger arrays this will (probably) be slower than a Fisher-Yates shuffle too. The shuffle will be O(n) whereas using sort will (probably) be O(n log n). – LukeH Sep 15 '10 at 17:22
  • 2
    @LukeH OK, you are right. But this is more beautiful :P – pepkin88 Sep 15 '10 at 20:02
  • This is a very clean and elegant solution. Take my upvote... – Colin Aug 07 '21 at 01:48
7

I found this post on using the Fisher-Yates algorithm to shuffle an array in JavaScript. It uses this function:

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}
gnarf
  • 105,192
  • 25
  • 127
  • 161