taiwoorogbangba taiwoorogbangba - 4 months ago 29
HTML Question

Options shuffle each time a webpage is reloaded

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?

Answer

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