Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Trivial question. What I have so far http://jsfiddle.net/Dth2y/1/

Task, the next button should randomly select a value from the array and remove that value from the array. So far this called the getNames function, within this function the value randomly selected from the array should be removed too after being appended to the html.

HTML

<h1 id="name">Click Next To Start</h1> <button id="next">NEXT NAME</button> <button>SKIP NAME</button>

JS

     $(document).ready(function() {
     var names = [
         "Paul",
         "Louise",
         "Adam",
         "Lewis",
         "Rachel"
     ];

     function getNames() {
        return names[Math.floor(Math.random() * names.length)];

     }

             $("#next").click(function() {
                 $('#name').text(getNames())

     });
 });

I have seen similar questions using the splice method, I have tried to hack a version together but am wondering if there's a more efficient way.

share|improve this question
    
show the splice code you tried. Method is likely one of simpler solutions. WOuld also need to check if array has length and do something different if all names used up –  charlietfl Dec 22 '12 at 20:55

2 Answers 2

up vote 2 down vote accepted

you will want to check this out: http://ejohn.org/blog/javascript-array-remove/

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

here it is applied to your fiddle: http://jsfiddle.net/Dth2y/3/

share|improve this answer

You could instead randomly shuffle the array before-hand and then pop() the first element or shift() the last element.

/**
 * Shuffles an array in-place
 */
function shuffle(array) {
    for (var i = array.length-1; i > 0; --i) {
        // Select a random index 0 <= j <= i
        var j = Math.floor(Math.random() * (i+1));
        // Swap elements at i and j
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

$(document).ready(function() {
    var names = [
        "Paul",
        "Louise",
        "Adam",
        "Lewis",
        "Rachel"
    ];

    // Shuffle the names
    shuffle(names);

    $("#next").click(function() {
        // Grab the next name and remove it
        $('#name').text(names.pop());
    });
});

(The shuffle function is based on the Fisher-Yates shuffle algoritm. This post explains how it works.)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.