0

I want to have shuffled answers in a quiz and they do shuffle but there's a problem. There can be one answer displayed four times (that's how much answers I have to each question), so it repeats and I'm not sure how to fix it.

`

function showQuestion() {
    /*Show a question*/
    let headerTemplate = `<h2 class="title">%title%</h2>`;
    let title = headerTemplate.replace('%title%', questions[questionIndex].question);
    headerContainer.innerHTML = title;

    /*Show answers*/
    let answerNumber = 1;
    for (var item of questions[questionIndex].answer) {
        const questionTemplate = `<li>
        <label>
           <input value="%number%" type="radio" class="answer" name="answer">
           <span>%answer%</span>
        </label>
        </li>`;

        let answers=questions[questionIndex].answer;
        function shuffle(answers) {
            let currentIndex = answers.length,  randomIndex;
            while (currentIndex != 0) {
              randomIndex = Math.floor(Math.random() * currentIndex);
              currentIndex--;
              [answers[currentIndex], answers[randomIndex]] = [
                answers[randomIndex], answers[currentIndex]];
            }
          
            return answers;
          }
          
          shuffle(answers);
          
        let i=0;
        let answerText = questionTemplate.replace('%answer%', answers[i]).replace("%number%", answerNumber);
        i++;
      
        listContainer.innerHTML += answerText;
        answerNumber++;
    }

`

I think the answer could be here somewhere

I tried doing it in a for loop and using math.floor, math.random

pozhara
  • 13
  • 1
  • 5
    Does this answer your question? [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/q/2450954/328193) – David Nov 18 '22 at 14:22
  • Imagine putting your elements (questions) in a hat (an Array), and then randomly (`Math.floor(Math.random() * questionsRemainingInHat.length)`) picking an element out of the hat until the hat is empty. – Ben Aston Nov 18 '22 at 14:27
  • `if(answers[i]===answers[i])` this will always be true. No need to check. – James Nov 18 '22 at 15:05

0 Answers0