I'm trying to grab 3 random answer from an array of answers and store them into a new array. So pretty much the new array which is selectedAnswers will have 3 random answers from the pool of answers, plus the correctAnswer. I think I some what got it, but the only problem is, I don't know how to make it skip if an array element is already used, and add a different one instead. So I end up having duplicates in my new array.
see the code here.
http://jsfiddle.net/oybojgzm/2/
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();