I have this snippet in my class that use chance.js to generate a random number:
this.askQuestions = [];
this.questions = JSON.parse(this.questionsData);
for(let i = 0; i < 10; i++){
let n = chance.integer({min: 0, max: this.questions.length - 1});
this.askQuestions.push({
questionIndex: n,
question: this.questions[n].question,
choices: this.questions[n].possibleAnswers
});
}
I'm using it to extract random questions from a json file that have 2000+ entries. During the debug I've set the fixed number of 10
iterations bur I'm working to let the user set a number between 1 and 100. I've noticed that sometimes I will have some questions duplicated and I don't want that this can occur. Can anyone suggest me a way to check and eventually replace duplicated entries into the questions array?
You can use unique()
method on chance
object to get unique integers.
this.askQuestions = [];
this.questions = JSON.parse(this.questionsData);
const questionNumbers = chance.unique(chance.integer, 100, {min: 0, max: this.questions.length - 1})
for(let i = 0; i < 10; i++){
let n = questionNumbers[i];
this.askQuestions.push({
questionIndex: n,
question: this.questions[n].question,
choices: this.questions[n].possibleAnswers
});
}