mardi 10 octobre 2017

How to check if an item has appeared in an array and reselect something new if it has?

Ok, so I thought I was doing this right but evidentially something is going wrong because my code runs forever. Please bear in mind I'm in high school and new to coding so there might be a very easy solution to this, but I can't work it out.

I have a datafile, which has various question data in it. My aim is to randomly choose a single question from the data and then check the id of the question against an array of id's. If the id appears in that array, I want to re run the random selection function to choose another question. I want to keep doing this until I have a question which has not appeared.

var dataFile = { 
'01': { questionID: '00100A', text: 'Random question number one?'},
'02': { questionID: '00200B', text: 'Random question number two?'},
'03': { questionID: '00300C', text: 'Random question number three?'},
'04': { questionID: '00400D', text: 'Random question number four?'},
'05': { questionID: '00500E', text: 'Random question number five?'},
'06': { questionID: '00600F', text: 'Random question number six?'},
'07': { questionID: '00700G', text: 'Random question number seven?'},
'08': { questionID: '00800H', text: 'Random question number eight?'},
'09': { questionID: '00900I', text: 'Random question number nine?'},
'10': { questionID: '01000J', text: 'Random question number ten?'}};

var questionsAsked = ['00100A', '00300C', '00500E', '00700G', '00900I'];

const keys = Object.keys(dataFile).map(key => dataFile[key]);

let selectedQuestion = keys[Math.floor(Math.random() * keys.length)];

let questionID = (selectedQuestion.questionID)

if (questionsAsked.includes(questionID)) {
  let selectedQuestion = keys[Math.floor(Math.random() * keys.length)];
  return selectedQuestion;
} else {
  questionsAsked.push(questionID);
  return selectedQuestion;
}

The data file has 9 pieces data in it. There is also an array of questions that have already been asked. I first map the dataFile to get the question data, then select a single random question from that. I pull the questionID from that question and then use an if...else statement to check whether that questionID appears in the questionsAsked array. If it does, I reselect another single question. If it doesn't, the id is pushed into the array and the questions is returned.

My issue is that if the if statement is true, another question is selected but never checked again to see if it appears in the questionsAsked array. Also tried a while loop to see if that made any difference but thats when my code got stuck in an infinite loop.

while (questionsAsked.includes(guID)) {
  let selectedQuestion = keys[Math.floor(Math.random() * keys.length)];
  let questionID = (selectedQuestion.questionID);
}

questionsAsked.push(guID);
return selectedQuestion;

Any suggestion would be very much appriciated

Aucun commentaire:

Enregistrer un commentaire