JavaScript: creating and saving unique random selections without repetition

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;

Answer №1

The logic for your filter condition seems to be inverted. You should be looking for values that are not equal to bar_a.

Additionally, make sure to update array.filter to foo.filter.

    // Array with values to assign randomly to A or B
    var foo = ["a", "b", "c", "d"];

    // Variables to store the values for A and B
    var bar_a=  [""];
    var bar_b=  [""];
    
    // Randomly select value from foo and assign to A
    bar_a = foo[Math.floor(Math.random()*foo.length)];
    
    // Remove the selected value from the array to create a new one
    var foo_filtered = foo.filter(function(value, index, arr){
        return value !== bar_a;
    });

    // Randomly select value from foo_filtered and assign to B
    bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];

    // Assign values to placeholders in an HTML table (a1, b1)
    document.getElementById("a1").innerHTML = bar_a;
    document.getElementById("b1").innerHTML = bar_b;
A: <span id="a1"></span>   B: <span id="b1"></span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Constructing a form by employing the directive approach to incorporate various input fields

My goal is to create input fields that capture information when the submit button is clicked using the directive method. These values will then be passed as arguments to a function. However, my current code is not functioning as expected. <!DOCTYPE htm ...

Python-JavaScript Integration Problem

I'm a beginner when it comes to Javascript, Python, and PHP. In my Javascript program, I have a button that triggers a Python script and displays the returned value on the screen. My goal is to steer clear of using Jquery and Json. Here are the snipp ...

Loading content from another webpage within a webpage using Ajax

I successfully implemented an Ajax chat in a PHP page and it was working perfectly. However, when I tried to integrate the chat into another page using a pop-up div (via CSS with z-index), I encountered some issues. Here is the code snippet: function sho ...

Should mutators be encapsulated within a class contained in a JS Module for better code organization and maintainability?

In order to maximize functionality of our new product using JavaScript, we have implemented an Authentication module that manages a tokenPromise which is updated upon user logins or token refreshes. It seems imperative to allow for mutation in this process ...

How can componentsProps be utilized within Material-UI components?

While going through the API documentation of components like AutoComplete, StepLabel, and BackDrop, I came across the componentsProps property. However, I haven't found a clear explanation or example of how to use this prop effectively. If anyone cou ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

What is the best way to divide text into key-value pairs using JavaScript?

I have data in text format from my Raspberry Pi that I need to insert into MongoDB as key-pair values or JSON for my Node.js Application. I'm relatively new to JavaScript and I'm looking for a solution. Any suggestions would be greatly appreciate ...

Error: Attempting to access the properties `line_items.amount`, `line_items.currency`, `line_items.name`, `line_items.description`, or `line_items` is not allowed

Hi there, I'm currently working on creating an Amazon-inspired platform and I've encountered an error while trying to integrate Stripe with the project. Can anyone provide some assistance? You can refer to the video tutorial I'm using by fol ...

I'm encountering difficulties in utilizing Ajax to upload images

I have been attempting to utilize ajax and bootstrap (modal) to add a new product. However, when I click the save changes button, I encounter an issue where all fields return an error message stating 'Undefined index'. Below is the code snippet ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Personalizing Google Map pin

I found some code on Codepen to add pointers to a Google map. Currently, it's using default markers but I want to change them to my own. However, I'm not sure where in the code to make this update. Any examples or guidance would be appreciated. ...

NextJs Link component does not refresh scripts

While using the <Link> tag in NextJs for page navigation, I encountered an issue where my scripts do not rerun after switching pages. The scripts only run on the initial page load or when I manually reload the page. This behavior is different when us ...

Transforming dynamic tables into JSON format

Whenever a user adds a new row to the dynamic table to input customer information, I require the data to be submitted in JSON format upon clicking the submit button. HTML <table class="table table-bordered table-hover" id="driver"> ...

creating an array within a Java for loop

public class Test1 { public static void main () { int N = 10; int M = 100000; for(int i =0; i< N; i++) { int[] box = new int[M]; } } } Does this code result in memory being allocated for an array of ...

Tips for zooming to the middle of a div element

I'm trying to figure out how to create a zoom in effect on my large div, but I haven't been successful despite searching through many resources. My goal is to zoom into the center of the user's screen rather than just at a set position. ht ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

What are the steps to integrating JavaScript autocomplete into a website?

I am relatively new to the world of programming, particularly when it comes to JavaScript/jQuery. I have been searching online for a solution to enable autocomplete in my search feature, but despite trying various approaches found on the internet, I have y ...

Activate function on Selected DIV

Within this div, I have set the tabindex attribute to '-1' so that it can be focused on mouse click. <div tabindex='-1'></div> .div:focus{//some style} My goal is to use jQuery to perform an action when a user clicks on th ...

Anticipated that the absence of a value would match the presence of an Object

Struggling with running AngularJS unit tests for $resource using Jasmine v2.0 and Karma v0.13, I managed to convert custom actions to newer syntax successfully. However, a specific type of test is giving me trouble, which I suspect is related to $httpBacke ...

Error message malfunction on the Express.js server side

Here is the server-side POST code that I am using. Before saving my task to the database, I am trying to find data in the database using a unique value called service. However, when I run this code, the console displays an error: ReferenceError: service is ...