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

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -