Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
How do i generate a random question using javascript for my quiz app which doesn't repeat the same question

I am trying to generate random questions from my "questions" object which does not repeat it's self but my quiz app is repeating questions.

Please forgive me if my question is not clear enough. This is my first ever time asking a question or really using stack overfolow,

let selectedQuestions = [];

//creates random index between 0 and the length of any array passed into it
const getRandomIndex = (arr) => Math.floor(Math.random() * arr.length);

//uses getRandomIndex to generate select a random object from and array. Also checks to see if the random object has been selected, if not, pushes the question to the empty selectedQuestions array and if selected, loops through its own function with a recursion by calling itself until it finds a question that has not already been pushed to the selectedQuestions array.
const getRandomObject = (arr) => {
  const random = getRandomIndex(arr);
  if (selectedQuestions.includes(random)) {
    getRandomObject(arr);
  }
  selectedQuestions.push(random);
  console.log("selected questions:", selectedQuestions.length)
  return arr[random];

  //renders the selected array and questions in the correct section of the quiz board.
  const randomGenerator = () => {
    const data = getRandomObject(questions);
    progress.textContent = `Question ${gameState.questionCounter} of ${maxQuestion}`
    questionBoard.textContent = `Q${gameState.questionCounter}. ${data.question}`;
    currentCorrectAnswer = data.answer;
    userAnswer.forEach((answer, index) => {
      answer.innerHTML = `${alphabet[index]}. ${data.choices[index]}`;
    });
    currentUserAnswer = null;
    clearAll()

    gameState.questionCounter++
      nextBtn.disabled = true;

    setDisabledStateForQuizAnswers(false);
  }
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're missing a return statement in the getRandomObject function.

if (selectedQuestions.includes(random)) {
  return getRandomObject(arr);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda