I’m working on a web application where users can take a quiz. I’m currently using twenty questions and I want the options to shuffle each time the page is refreshed. How can I do this using JS or any of its frameworks?
Asked
Active
Viewed 73 times
0
-
do you need a specific order, or a guarantee of not repeating a given pattern? – dandavis Jul 08 '16 at 20:21
-
Assuming your questions are in an array like object you probably want to shuffle them http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript – JonSG Jul 08 '16 at 20:39
-
@JonSG interesting; I tried this solution (or a similar one) and it wouldn't scramble an array of objects: https://jsfiddle.net/5019mgu2/1/ – Patrick C Jul 08 '16 at 20:46
-
@dandavis, I don't want any pattern repeated. – taiwoorogbangba Jul 08 '16 at 20:54
-
then you need to sort on the server and record which orders have been used. Also, it might not be ethical to show different students different ordering: some could get stuck on a hard question at first, which leaves them less time to answer other questions than students who answer the hard one last. – dandavis Jul 08 '16 at 20:57
-
@dandavis, what if I use a specific order? Is there a way I can do that from the front end? – taiwoorogbangba Jul 08 '16 at 20:59
1 Answers
1
Did you try something like this?
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var questions = [
{ id: 1, name: "question 1" },
{ id: 2, name: "question 2" },
{ id: 3, name: "question 3" },
{ id: 4, name: "question 4" },
{ id: 5, name: "question 5" }
];
shuffleArray(questions);
questions.forEach(function(question){ console.log(question.name); });

JonSG
- 10,542
- 2
- 25
- 36