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

111
Visualizações
Javascript function that Shuffle/Random an array excluding given index
const questions = [
    {
      questionText: <img src={`img//${question[0].image}`} />,
      answerOptions: [
        { answerText: <img src={`img/${answer[Math.floor(Math.random() * 11)].image}`} />, isCorrect: false },
        { answerText: <img src={`img/${answer[Math.floor(Math.random() * 11)].image}`} />, isCorrect: false },
        { answerText: <img src={`img/${answer[0].image}`} />, isCorrect: true },
        { answerText: <img src={`img/${answer[Math.floor(Math.random() * 11)].image}`} />, isCorrect: false },
      ]
    }
]

For example in the quiz array, instead of Math.floor(Math.random() * 11) which generates number from 0 to 11, it should exclude 0 index so that answer list is not same. Also how to have the other answers with different index number.

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

0

Use splice to remove the correct answer from the array, then shuffle, then use splice again to insert the element back:

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

const answerOptions = [
        { answerText: 'A', isCorrect: false },
        { answerText: 'B', isCorrect: false },
        { answerText: 'C', isCorrect: true },
        { answerText: 'D', isCorrect: false },
]

const correctAnswerIndex = answerOptions.findIndex(answer => answer.isCorrect);
const removed = answerOptions.splice(correctAnswerIndex, 1);
shuffleArray(answerOptions);
answerOptions.splice(correctAnswerIndex, 0, ...removed);
console.log(answerOptions);

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