javascript - Randomly generate name from Array with zero repeat? -


update: difference i'm not trying make 1 list i'm trying make button can clicked , generate random name

goal: click button , randomly generate name array. i'm trying able click button , show 1 name randomly @ time no repeating names. far i've been able randomly select name names still repeat. how change code avoid repeating names?

 $( ".next").click(function() {      $(".intro").hide()      var people = ["andrew", "adam", "seth", "mattos", "eric"];     for(i=0;i<1;i++){     var randomposition = math.floor(math.random() * people.length);     var selected = people.splice(randomposition,1);     console.log(selected)      $('#person').text(selected)       if ($('#person').text() === "mattos"){         $("#selectedperson").text("mattos")     }     if ($('#person').text() === "andrew"){         $("#selectedperson").text("andrew")     }     if ($('#person').text() === "eric"){         $("#selectedperson").text("eric")     }      if ($('#person').text() === "seth"){         $("#selectedperson").text("seth")     }     if ($('#person').text() === "adam"){         $("#selectedperson").text("adam")     }     }     }); 

the problem you're creating array every time enter function. splicing name out of array has no effect, because you'll refill next time. need move array initialization out of function.

other issues: splice() returns array, not single element, if you're splicing out 1 element array. don't need for() loop if you're looping 1 time. if statements unneeded, since you're assigning same strings in cases.

and should check case you've run out of names.

var people = ["andrew", "adam", "seth", "mattos", "eric"];  $( ".next").click(function() {     $(".intro").hide();     if (people.length == 0) { // no names left show         return;     }     var randomposition = math.floor(math.random() * people.length);     var selected = people[randomposition];     people.splice(randomposition,1);     console.log(selected)      $('#person,#selectedperson').text(selected); }); 

Comments