[Vuejs]-Randomising the answers in a multiple choice quiz game

0👍

You could use a famous algorithm called Fisher-Yates Algo to randomize items in an array extremely quickly and efficiently, if thats the route you want to take. It takes the following form:

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

0👍

If you create a computed property, containing the shuffled version of your answers array, you can then use v-for to render each of these answers. For the actual shuffling logic, you can see this question.

Here’s a basic example:

computed: {
  answers() {
  return this.answers
    .map(value => ({ value, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(({ value }) => value);
  }, 
},
<td v-for="(answer, index) in answers" :key="index">
  <button type="button" class="btn" class="button" @click="checkAnswer(answer)">{{ answer }}</button>
</td>

Leave a comment