Random questions of an array

0

I have a test with a set of questions-answers. I would like for a set of 3 questions to only show 2 randomly.

I think the code I have to use is the following, but I have no idea where I have to place it: Math.floor(Math.random() * myQuestions.length)

This is the JS of I want to select the two questions:

(function() {
function buildQuiz() {
  const output = [];

  myQuestions.forEach((currentQuestion, questionNumber) => {
    const answers = [];

    for (var letter in currentQuestion.answers) {
      answers.push(
        '<label>
    <input type="radio" name="question${questionNumber}" value="${letter}">
    ${letter} :
    ${currentQuestion.answers[letter]}
  </label>'
      );
    }

    output.push(
      '<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>'
    );
  });

  quizContainer.innerHTML = output.join("");
}
const quizContainer = document.getElementById("quiz");
const myQuestions = [{
    question: "Who is the strongest?",
    answers: {
      a: "Superman",
      b: "The Terminator",
      c: "Waluigi, obviously"
    },
    correctAnswer: "c"
  },
  {
    question: "What is the best site ever created?",
    answers: {
      a: "SitePoint",
      b: "Simple Steps Code",
      c: "Trick question; they're both the best"
    },
    correctAnswer: "c"
  },
  {
    question: "Where is Waldo really?",
    answers: {
      a: "Antarctica",
      b: "Exploring the Pacific Ocean",
      c: "Sitting in a tree",
      d: "Minding his own business, so stop asking"
    },
    correctAnswer: "d"
  },

];
    
asked by Antonio Andrés 10.02.2018 в 20:34
source

1 answer

0

You could randomly remove 1 item from the array. Using splice()

 var indice = Math.floor(Math.random() * output.length);
 output.splice(indice, 1);

In general terms the above could be repeated to remove N elements of a universe M.

In terms of efficiency it may be advisable to first decide which questions will go and then process them in your output array.

    
answered by 10.02.2018 / 21:08
source