I am trying to use Javascript to create an array, take two unique random draws from the array, then assign the drawn values to an HTML table. My approach has been to create an array, take a random, create a new array without the drawn value, then take a random draw from the new array as a way of taking two random draws without replacement.
I have provided a minimal example of what I've done to accomplish this, but it's not working. I would like the values assigned to the HTML table to ultimately be two unique values (e.g. "a", "b") from the foo array. Is this not working because value == bar_a below won't remove the value assigned to the bar_a array because bar_a is an array and not the value of the array?
While this post has addressed drawing without replacement, it doesn't provide an example when using strings or explain how to save both numbers and it's unclear why they're using splice()
rather than filter()
// Define array containing the set of values we'll randomly assign to A or B
var foo = ["a", "b", "c", "d"];
// Initialize variables to hold the value for A and B
var bar_a= [""];
var bar_b= [""];
// Randomly draw from foo, save for A
bar_a =foo[Math.floor(Math.random()*foo.length)];
// Remove the drawn value from the array, create new array
var foo_filtered = array.filter(function(value, index, arr){
return value == bar_a;
});
// Randomly draw from foo_filtered, save for B
bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];
// Assign attributes and values to their placeholders (a1, b1) in a HTML table
document.getElementById("a1").innerHTML = bar_a;
document.getElementById("b1").innerHTML = bar_b;
Aucun commentaire:
Enregistrer un commentaire