Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda