Kanyar Kanyar - 1 year ago 79
Javascript Question

How to generate 3 names without the same name repeated

window.onload = start;

function start () {
var name = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"]
var random = Math.floor(Math.random()*8)
var random2 = Math.floor(Math.random()*8)
var random3 = Math.floor(Math.random()*8)
var name2 = []

for(i=0; i<3; i++) {
document.getElementById("par").innerHTML += name2[i] + "<br/>" ;

So far with this code i can generate 3 random names from the name array. But i want the 3 names not to be repeated, and I don't know how to make that happen.

Answer Source

Replace the assignment for random2 and random 3 with:

var random = Math.floor(Math.random()*8);
var random2, random3;
do { 
  random2 = Math.floor(Math.random()*8);
  } while (random2==random);

do {
  random3 = Math.floor(Math.random()*8);
  } while (random3==random || random3==random2);

Try it out here: https://jsfiddle.net/o04tf9ct/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download