Skip to content
Advertisement

What’s the best way of getting each item from an array in order?

I am currently building a quiz based on a code that I’ve found online, tweaking a couple things, and this specific line it grabs the quiz questions from the array using Math.random to randomize the questions:

getNewQuestion = () => {
    questionCounter++;
    const questionIndex = Math.floor(Math.random() * availableQuesions.length);
    currentQuestion = availableQuesions[questionIndex];
    question.innerText = currentQuestion.question;
}

Advertisement

Answer

All you have to do is keep track of the current question index, and increment it as you grab questions. Similar to your questionCounter keep track of questionIndex globally and only increment it when you are grabbing a new question from the bank.

To grab from the bank all you need to do is availableQuestions[questionIndex] as you have, and you could even combine the incrementation and grabbing like this

availableQuestions[questionIndex++]

just make to define questionIndex globally and initialize it at 0.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement