1

Possible Duplicate:
How to remove first element of an array in javascript?

function write() {
    for (var x = 1; x <= 3; x++) {
        var question = new Array("If you are goofy which is your leading foot", "Riding switch is when you do what", "On your toe side which way should you lean", "question 4", "question 5", "question 6");

        var l = question.length;

        var rnd = Math.floor(l * Math.random());

        document.write(question[rnd]);
        document.write("<br>")
    }

}

This is my code but it outputs the same question(string) sometimes when i want the three questions to be unqique, how do i remove an element from the array after its output?

0

4 Answers 4

3

You need to use the array's splice() method. However, you're creating a new array every iteration, so you need to move that part out of the loop.

function write() {
    var questions = [
        "If you are goofy which is your leading foot",
        "Riding switch is when you do what",
        "On your toe side which way should you lean",
        "question 4",
        "question 5",
        "question 6"
    ];

    for (var x = 1; x <= 3; x++) {
        var rnd = Math.floor(questions.length * Math.random());
        document.write(questions[rnd] + "<br>");
        questions.splice(rnd, 1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try:

question.splice(rnd,1)

Put this at the end of your loop, and it will remove the element that has just been displayed.

Comments

0

Instead of removing an element from the array you could keep track of the random indices which you have already used and avoid them. Something like this:

function write() {
  for (var x = 1; x <= 3; x++) {
    var question = new Array(...);
    var used={}, l=question.length, rnd;
    do {
      rnd = Math.floor(l * Math.random());
    } while (rnd in used);
    used[rnd] = true;
    document.write(question[rnd]);
    document.write("<br>")
  }
}

Comments

0

I agree with Tim's response. In addition, though, you can compact the code a little bit more by doing it like this:

function write() {
  var question = ["If you are goofy which is your leading foot", "Riding switch is when you do what", "On your toe side which way should you lean", "question 4", "question 5", "question 6"];

  for (var x = 1; x <= 3; x++) {
    var rnd = Math.floor(question.length * Math.random());
    document.write(question.splice(rnd, 1)[0] + "<br>");
  }
}

The reason the above code will also work is because splice not only removes the element, but also returns the sub-array that was removed.

1 Comment

If you are a big fan of writing long lines of code, you can even move the random number generation into the position of the first parameter of the splice function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.