mercredi 3 février 2021

how to pull random strings from an array with no repeats in javascript?

i'm very new to javascript and working on making a random generator that runs in a browser, and i think i have things mostly figured out, except i can't figure out how to ensure there are no repeats between random strings.

i was thinking maybe removing the first result from the array so the second can't pick it (preferable, because in the final code there will be multiple variables pulling from the same array in multiple different configurations, and several arrays being pulled from in this way; but idk if that's possible?), or maybe having the second one rerun until it gets something unique.

however, i, uh, don't know how to do either of these things, and no amount of googling has given me anything both relevant and understandable enough (as a beginner) for me to successfully apply ^^; any help?

this is a simplified version of my code to just include relevant stuff, let me know if i need to provide more

<button onclick="random()">GENERATE</button>

<p id="text"></p>

<script>
var canids = ["dog", "wolf", "coyote", "jackal", "fox", "wild dog", "raccoon dog", "dire wolf", "dingo"]
function random() {
var canids1 = canids[(Math.random() * canids.length) | 0]
var canids2 = canids[(Math.random() * canids.length) | 0] /*i want it to be impossible for this to be the same as canids1*/

document.getElementById('text').innerHTML = canids1 + " " + canids2;
}
</script>



Aucun commentaire:

Enregistrer un commentaire