Reputation: 11
I'm making a quiz. I try to find a way to generate non repeating random numbers from an array. How can help me?
This is what I have:
questions = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7"]
var randoms001 = Math.floor(Math.random() * questions.length);
Upvotes: 1
Views: 57
Reputation: 2832
Shuffle the array and loop through it.
var questions = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7"];
var shuffledQuestions = randoSequence(questions);
for(var i = 0; i < shuffledQuestions.length; i++){
console.log( shuffledQuestions[i].value );
}
<script src="https://randojs.com/1.0.0.js"></script>
I used randojs.com to do the shuffle in a simple and readable way, but feel free to shuffle it yourself if you that's your preference.
If you choose to use randojs, just make sure this is in the head of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
Upvotes: 1