Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  36] [ 5]  / answers: 1 / hits: 36178  / 14 Years ago, wed, september 15, 2010, 12:00:00

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.


More From » json

 Answers
10

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

[#95614] Monday, September 13, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;