-3

I'm rather new to HTML/CSS/JS... I've seen functions to randomize quiz questions however can't make any of the solutions work with the code I already have.

I would really appreciate someone showing me a way to randomize the questions displayed. And would also like a brief description on why it works.

This is not classwork/coursework... I'm trying to create a quiz for a series of classes I'm taking for work.

Thank you in advance :)

This code works but does not randomize the questions. Questions are store in 'questions.js' and look like this:

questions.js

{
        numb: 7,
        question: "The property tax is an ______   ______ tax, meaning it is based on value.",
        answer: "B. ad valorem",
        options: [
            "A. carpe diem",
            "B. ad valorem",
            "C. vino veritas",
            "D. non verba"
        ]
    },

script.js

    const questionText = document.querySelector('.question-text');
    //    questionText.textContent = `${questions[index].numb}. ${questions[index].question}`;
    questionText.textContent = `${questions[index].question}`;
    let optionTag = `<div class="option"><span>${questions[index].options[0]}</span></div>
    <div class="option"><span>${questions[index].options[1]}</span></div>
    <div class="option"><span>${questions[index].options[2]}</span></div>
    <div class="option"><span>${questions[index].options[3]}</span></div>`;```
WillWalsh
  • 193
  • 2
  • 12

1 Answers1

1

To get a random questions, its about generating a random index between zero and the length of the questions.js array Try the following code

// To ensure uniqueness, store the generated integer in a Set
const uniqueNumbersSet = new Set();

function getRandomIndexFromArray(arr) {
  const randomIndex = Math.floor(Math.random() * arr.length);

  // If the generated integer is not unique, keep generating new ones until it is unique
  while (uniqueNumbersSet.has(randomIndex)) {
    const newRandomIndex = Math.floor(Math.random() * arr.length);
    randomIndex = newRandomIndex;
  }

  // Store the unique integer in the Set
  uniqueNumbersSet.add(randomIndex);

  return randomIndex;
}

Usage:

const randomIndex = getRandomIndexFromArray(YOUR-QUESTIONS-LIST)

Now use the randomIndex to append in your script.js instead of index

Don't forget to empty the uniqueNumbersSet after you finish your quiz.