Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Shuffling Objects inside an object (randomize) [duplicate]

Tags:

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.

like image 292
easement Avatar asked Sep 15 '10 13:09

easement


People also ask

How do you shuffle an object in JavaScript?

The first and simplest way to shuffle an array in JavaScript is to provide a custom function to a . sort() . const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const shuffledArray = array. sort((a, b) => 0.5 - Math.

How do you shuffle an object array?

Shuffle Array using Random Class We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

Is there a shuffle function in JavaScript?

In contrary to languages like Ruby and PHP, JavaScript does not have an built-in method of shuffling the array. However, there is a method that allows shuffling the sequence. Let's discuss a particular case. Shuffling an array of values is considered one of the oldest problems in computer science.


1 Answers

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; } 
like image 152
LukeH Avatar answered Oct 23 '22 06:10

LukeH