0

I'm making a test that contains questions.

I want the questions to come up on the page randomized rather than in an ordered list.

Here is my HTML:

<ol id = "questionList">
<li id="question">Question text<br/></li>
<li id="question">Question text<br/></li>
</ol>

Here is my javascript:

var questionsList = document.getElementById('question');
var questionArray=[];
var randomize;

for (var i=0; questionsList.length>0; i++) {
        questionArray[i]=questionList[i];
}
randomize = questionArray.Math.random()*questionList.length;

document.getElementById("questionsList").innerHTML= randomize;

I cant figure out how to get the questions to appear randomly rather than from #1 down to #10.

Any help is appreciated.

Andrew Hendrie
  • 6,205
  • 4
  • 40
  • 71
TheNamesZero
  • 39
  • 10

1 Answers1

1

Question has already been asked (How to randomize (shuffle) a JavaScript array?)

But here's the basics:

A solid shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

See https://github.com/coolaj86/knuth-shuffle

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

You can use it like this:

var arr = ["question 1", "question 2"];
shuffle(arr);
console.log(arr);
Community
  • 1
  • 1
Andrew Hendrie
  • 6,205
  • 4
  • 40
  • 71