newbiedev
newbiedev

Reputation: 3586

Javascript - avoid duplicated questions into an array

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?

Upvotes: 0

Views: 62

Answers (2)

Punith Mithra
Punith Mithra

Reputation: 628

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
        });
    }

Upvotes: 1

Robo Robok
Robo Robok

Reputation: 22755

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
    });
}

Upvotes: 1

Related Questions