Avoid duplicate elements in a random array from a string in javascript -


now, let known i've looked on , i've been unable find answer specific problem i've got. i'm new js , i've been trying teach myself, i'm making basic, "noob" mistake.

so apologies in advance.

i'm trying make "random generator" of sorts, pulling 2 words given list , i'm not quite sure how avoid duplicate results appearing.

i suppose i'm doing wrong in following code:

var randomdiv = document.getelementbyid("myrandomdiv");  document.getelementbyid("mybutton").addeventlistener("click", function() {       randomindex = math.ceil((math.random()*randomstrings.length-1));       randomindex2 = math.ceil((math.random()*randomstrings.length-1));       newtext = randomstrings[randomindex]+" + ";       newtext2 = randomstrings[randomindex2];       randomdiv.innerhtml = newtext+newtext2; 

you need keep fetching randomindex2 till different value

replace

randomindex2 = math.ceil((math.random()*randomstrings.length-1)); 

with

randomindex2 = math.ceil((math.random()*randomstrings.length-1)); while( randomindex == randomindex2 ) {    randomindex2 = math.ceil((math.random()*randomstrings.length-1)); } 

Comments

Popular posts from this blog

Load Balancing in Bluemix using custom domain and DNS SRV records -

oracle - pls-00402 alias required in select list of cursor to avoid duplicate column names -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -