I am working on a random question generator and am trying to take 5 questions from a large array of objects that looks like this:
const bank= [
{
txt: "This question's unique text...",
choices: 'a', 'b', 'c',
answer: 2
},
{
txt: "This question has different text...",
choices: 'a', 'b', 'c',
answer: 1
},
// and so on for 20 more questions
I used a while loop to limit the number of iterations, I was hoping to limit the selection of exactly 5 objects selected. My loop:
//push the questions into availableQuestions Array
function setAvailableQuestions(){
const length = 5
const banklength = bank.length
while (length > banklength) { length = banklength}
for(let i=0; i<length; i++){
r = Math.floor(Math.random() * banklength)
availableQuestions.push(bank[r])
console.log(availableQuestions)
bank.splice(r, 1)
}
In the console, I see there is sometimes an 'undefined' object selected. I think it is because I have set up the 'splice'. Additionally, it is iterating 25 times rather than 5. I have been stuck for a couple of days on this . After searching, I have learned about the Fisher-Yates shuffle and tried to run that function first and push the first five questions after, but that didn't work, either. Any point in the right direction is appreciated.