1

I borrowed a quiz's code from this site https://www.sitepoint.com/simple-javascript-quiz/ the thing is, I'm trying to get the questions to be displayed in a random order in the screen, rather than in the same order everytime. I've tried multiple ways but none seem to work, so help would be greatly appreciated. I'm guessing the solution lays in this function, but I'm not entirely sure what to modify.

function buildQuiz() {

// we'll need a place to store the HTML output
const output = [];

// for each question...

myQuestions.forEach((currentQuestion, questionNumber) => {
// we'll want to store the list of answer choices
const answers = [];

// and for each available answer...

for (letter in currentQuestion.answers) {
  // ...add an HTML radio button
  answers.push(
    `<label>
       <input type="radio" name="question${questionNumber}" value="${letter}" id="botones">
        ${letter} :
        ${currentQuestion.answers[letter]}
     </label>`
  );
}

// add this question and its answers to the output
output.push(
  `<div class="slide">
     <div class="question"> ${currentQuestion.question} </div>
     <div class="answers"> ${answers.join("")} </div>
   </div>`
);
});
  // finally combine our output list into one string of HTML and put it on the page quizContainer.innerHTML = output.join(""); }
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59

2 Answers2

0

You can use Math.random:

var questions = ['A','B','C','D','E']
var getRandomQuestion = (questions) => questions.pop(Math.floor(Math.random() * Math.floor(questions.length)));

console.log(getRandomQuestion(questions));
console.log(getRandomQuestion(questions));
console.log(getRandomQuestion(questions));
console.log(getRandomQuestion(questions));
Ziv Ben-Or
  • 1,149
  • 6
  • 15
0

Shuffle the questions array before proceeding.

var myQuestions = ['A','B','C','D','E']
function shuffle(array) {
  array.sort(() => Math.random() - 0.5);
}
shuffle(myQuestions);
console.log(myQuestions);
Jaydeep
  • 1,686
  • 1
  • 16
  • 29
  • Shuffle, yes, but [not with `Array.sort`](https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling). – AuxTaco Jun 25 '19 at 07:37
  • This seems like a perfect answer, but it still doesn't work, the quiz dissapears completely. I added that snippet right before the buildQuiz() function – azu sdhfjdg Jun 25 '19 at 12:24
  • @azusdhfjdg create a fiddle or something so that we can debug. – Jaydeep Jun 25 '19 at 12:27
  • @azusdhfjdg you are initializing myQuestions again. remove line number 32 and it will work. – Jaydeep Jun 25 '19 at 14:17
  • it still doesn't work but i don't quite understand why? – azu sdhfjdg Jun 25 '19 at 15:28
  • https://jsfiddle.net/imjaydeep/tngype9z/ updated the fiddle.. questions are coming randomly now.. @azusdhfjdg – Jaydeep Jun 26 '19 at 05:37