1

I would like to display randomly just 2 of the 3 questions (example as follows).

I know it is with Math.log() but I can't figure it out.

EDIT: I mean Math.random()

My idea is to have aprox. 100 questions and every time the quiz is attempted, just display 5. In this way, every time the quiz is different.

Here is the JavaScript code:

(function() {
function buildQuiz() {
  const output = [];

  myQuestions.forEach((currentQuestion, questionNumber) => {
    const answers = [];

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

    output.push(
      `<div class="question"> ${currentQuestion.question} </div>
    <div class="answers"> ${answers.join("")} </div>`
    );
  });

  quizContainer.innerHTML = output.join("");
}
const quizContainer = document.getElementById("quiz");
const myQuestions = [{
    question: "Who is the strongest?",
    answers: {
      a: "Superman",
      b: "The Terminator",
      c: "Waluigi, obviously"
    },
    correctAnswer: "c"
  },
  {
    question: "What is the best site ever created?",
    answers: {
      a: "SitePoint",
      b: "Simple Steps Code",
      c: "Trick question; they're both the best"
    },
    correctAnswer: "c"
  },
  {
    question: "Where is Waldo really?",
    answers: {
      a: "Antarctica",
      b: "Exploring the Pacific Ocean",
      c: "Sitting in a tree",
      d: "Minding his own business, so stop asking"
    },
    correctAnswer: "d"
  },

];
Antonio Andrés
  • 169
  • 2
  • 15

1 Answers1

0

Suppose you have a myQuestions array of size 3 and you want to randomly pick 2 questions from it. You can use Math.random() to select random indices from your array. For an array of size 3, you can do this as follows:

Math.floor(Math.random() * myQuestions.length)

You can call it twice to get two random indices and you can ask the questions corresponding to those indices. For a larger question set, you can do this random selection in a loop.

curlyBraces
  • 1,095
  • 8
  • 12