Skip to content
Advertisement

Pick and return a pair of values from an array into two different outputs. JavaScript

I have a function that takes a random element from an array and, at the press of a button, returns the random value to an output. The code is as follows:

const questions = ["What is your name?", "How old are you?", "Where are you from?"];
const randomQuestion = () => {
  let random = questions[Math.floor(Math.random() * questions.length)];

  document.getElementById("question").innerHTML = random;
};
<div>
  <output id="question" class="question"></output>
</div>

<button id="questionBtn" class="questionBtn" onclick="randomQuestion();">Ask</button>

So far the code is working perfectly, returning to the output a random value from the “questions” array. However, I need to take it a step further. I need to return two inseparable values from the array, and each of these values needs to be returned in a different output (the “questions” value goes to the “question” output, and the “examples” value goes to “example” output)

I therefore need to transform my “randomQuestion” function into one that returns, for example, the value “What is your name” for the output “question”, and the value “Matheus” for the output “example”, and so on.

const questions = [{
    question: "What is your name?",
    example: "Matheus"
  },
  {
    question: "How old are you?",
    example: "27"
  },
  {
    question: "Where are you from?",
    example: "Berlin"
  }
];

const randomQuestion = () => {
  let random = questions[Math.floor(Math.random() * questions.length)];
  document.getElementById("question").innerHTML = random;
};
<div>
  <output id="question" class="question"></output>
  <output id="example" class="example"></output>
</div>

<button id="questionBtn" class="questionBtn" onclick="randomQuestion();">Ask</button>

Advertisement

Answer

you were almost there

const questions = [{
    question: "What is your name?",
    example: "Matheus"
  },
  {
    question: "How old are you?",
    example: "27"
  },
  {
    question: "Where are you from?",
    example: "Berlin"
  }
];

const randomQuestion = () => {
  let random = questions[Math.floor(Math.random() * questions.length)];
  document.getElementById("question").innerHTML = random.question;
  document.getElementById("example").innerHTML = random.example;
};
<div>
  <output id="question" class="question"></output>
  <output id="example" class="example"></output>
</div>

<button id="questionBtn" class="questionBtn" onclick="randomQuestion();">Ask</button>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement