0

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?

Zam Abdul Vahid
  • 2,389
  • 3
  • 18
  • 25
newbiedev
  • 2,607
  • 3
  • 17
  • 65
  • Looks like you're looking for https://chancejs.com/miscellaneous/unique.html – georg Apr 26 '21 at 11:49
  • I've already saw it but the `chance.unique` function returns an array and I need a single number at a time :) – newbiedev Apr 26 '21 at 11:52
  • 1
    nope, you don't... instead of looping from 0 to N, generate N unique numbers and loop over these. – georg Apr 26 '21 at 11:55

2 Answers2

1

One of the ways to solve your problem without using any libraries would be to make an array of possible values and remove elements when they are randomly selected:

const N = this.questions.map((_, i) => i);

for (let i = 0; i < 10; i++) {
    const n = Math.floor(Math.round() * N.length);
    N.splice(n, 1); // remove N[n]

    this.askQuestions.push({
        questionIndex: n,
        question: this.questions[n].question,
        choices: this.questions[n].possibleAnswers
    });
}
Robo Robok
  • 21,132
  • 17
  • 68
  • 126
  • This is an interesting solution, it will give me tha ability to remove chance.js from the script dependencies but at the moment by using this way I will need to refactor all the code because I'm using chance also in other parts of the code – newbiedev Apr 26 '21 at 12:14
1

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
        });
    }
Punith Mithra
  • 608
  • 5
  • 9