简体   繁体   中英

Getting a 40 random values from a JavaScript array, Quizz App. I have in another file questions.js 3000 questions, I want to get random 40 questions

I want to get unique random 40 questions from questions.js anyone have suggestions.

//show Questions from array 
function showQuetions(index) {
  const que_text = document.querySelector(".que_text");

  //question tag add questions from another file
  let que_tag = '<span>' + questions[index].numb + ". " + questions[index].question + '</span>';
  let option_tag = '<div class="option"><span>' + questions[index].options[0] + '</span></div>' +
    '<div class="option"><span>' + questions[index].options[1] + '</span></div>' +
    '<div class="option"><span>' + questions[index].options[2] + '</span></div>' +
    '<div class="option"><span>' + questions[index].options[3] + '</span></div>';
  que_text.innerHTML = que_tag;
  option_list.innerHTML = option_tag;

  const option = option_list.querySelectorAll(".option");

  for (i = 0; i < option.length; i++) {
    option[i].setAttribute("onclick", "optionSelected(this)");

  }
}

The are multiples ways to do that :

shuffling array

The first method would be to shuffle the array and the take the first 40 questions.

You can write a pretty simple methods that suffle your array How can I shuffle an array

Random elements

You can also take 40 random elements (by taking a random integer between 0 and the number of questions you have and then removing that questions from the array.

Be sure to make a deep copy of the array before doing this

copy = Object.assign([],questions)

Then, do not forget to remove the question from the array to ensure not having the same question twice

Here is a snipper with both example :

 /** * Shuffles array in place. * @param {Array} a items An array containing the items. * From https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array */ function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; } const nbQuestions = 2 const questions = ["question 1","question 2","question 3","question 4","question 5","question 6"] //method 1 //deep copy let method1Questions = Object.assign([],questions) shuffle(method1Questions) let randomQuestions1 = method1Questions.slice(0,nbQuestions) console.log(randomQuestions1) //method 2 //deep copy let method2Questions = Object.assign([],questions) let randomQuestions2 = [] for (let i=0; i < nbQuestions; i++){ //random int let questionIndex = Math.floor(Math.random() * method2Questions.length) randomQuestions2.push(method2Questions[questionIndex]) method2Questions.splice(questionIndex,1) } console.log(randomQuestions2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM