Currently, I am grappling with using Javascript to generate an array, select two distinct random elements from the array, and then allocate these selected values to an HTML table. My strategy has involved initializing an array, picking a random value, generating a new array without the selected value, and then choosing another random value from this modified array to achieve two exclusive draws. Regrettably, my implementation of this tactic has not been successful. My goal is to display two distinct values (such as "a", "b") from the foo array in the HTML table. Could it be that the issue lies in value == bar_a when trying to eliminate the assigned value from the bar_a array because bar_a pertains to the array itself, not the actual value contained within it?
I have included a basic example of my efforts to achieve this outcome, but it appears to be flawed. While investigating on this post, I came across insights on sampling without replacement, specifically with numerical values, but it does not clarify how to preserve both values or explain the rationale behind using splice() over filter().
// Establish an array with a selection of values that will be randomly assigned to A or B
var foo = ["a", "b", "c", "d"];
// Define variables to store the values for A and B
var bar_a= [""];
var bar_b= [""];
// Randomly select an element from foo and assign it to A
bar_a =foo[Math.floor(Math.random()*foo.length)];
// Exclude the selected value from the array and create a new array
var foo_filtered = array.filter(function(value, index, arr){
return value == bar_a;
});
// Randomly pick an element from foo_filtered and assign it to B
bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];
// Assign the values to their designated placeholders (a1, b1) in an HTML table
document.getElementById("a1").innerHTML = bar_a;
document.getElementById("b1").innerHTML = bar_b;