Questions getting repeated

Viewed 71

I have made a random quiz through javascript and HTML, the questions are in a JSON file, but when I run the quiz it repeats some of the questions multiple times, how do I make it that no questions are repeated.

function renderQuestion(){
let index = Math.floor(Math.random() * availableQuestions.length);
runningQuestion = availableQuestions[index];
availableQuestions.pop(index);
let q = questions[runningQuestion];
question.innerHTML = "<p>"+ q.question +"</p>";
qImg.innerHTML = "<img src="+ q.imgSrc +">";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;

}

3 Answers

You are trying to remove an object from an array by using pop(index). This is not possible since pop will always remove the last element in the array (and does not accepts any parameters!).

Use Array.prototype.splice instead:

availableQuestions.splice(index, 1);  // Remove 1 element at specific index 

you could push the "index" into an array, like

const usedQuestions = [];

And then when u create a new index look through the "usedQuestions" index to not use them again.

Array.pop does not accept a parameter, passing the index is not doing anything here. It is simply popping the last element from the array.

Let's say you have question array qa = [a, b, c, d, e].

You generate a random index (index = 2) and set running question to that index (runningQuestion = qa[2], => runningQuestion = 'c'). You then pop an element and the array becomes qa = [a, b, c, d].

On the next function call, it is still possible to retrieve the question c.

I recommend the following approaches

  1. Randomize the array, and iterate over them
  2. Instead of pop, use splice
Related