Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!