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.
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);