I am attempting to select 3 random answers from an array of possible answers and store them in a new array. The new array, selectedAnswers, should contain 3 random answers along with the correctAnswer. While I have made some progress, I am facing an issue where I am unable to skip already used array elements and end up with duplicates in my new array.
You can view the code here.
var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];
var randomNumber = 0;
function randomAnswer() {
if (selectedAnswers.length < 4) {
randomNumber = Math.floor((Math.random() * answerList.length) +
1) - 1;
for (i = 0; i < answerList.length; i++) {
if (answerList[randomNumber] === answerList[i]) {
randomNumber = Math.floor((Math.random() * answerList.length) +
1) - 1;
randomAnswer();
} else {
selectedAnswers.push(answerList[i]);
console.log(selectedAnswers);
randomNumber = Math.floor((Math.random() * answerList.length) +
1) - 1;
randomAnswer();
break;
}
}
}
}
randomAnswer();