Create two tables using vanilla JavaScript

I am currently working on a program that randomly assigns Christmas gift-givers and receivers.

To facilitate this, I have set up two arrays: Players[] and Players2[]. When a player is added, their name is pushed into both arrays.

During the draw process, the program displays the names from Players[] on the left side and the drawn names from Players2[] on the right side. Once a Player from Players2[] is drawn, they are removed from the array, leaving it empty while keeping Players[] full.

However, I am struggling with implementing an if statement to ensure that a person does not draw themselves...

let Players = [];
let Players2 = [];

const addBTN = document.getElementById('addBTN');
const onlyLetters = /^[a-zżźćóęśńłA-ZŻŹĆÓŁĘŚŃŁ ]+$/;
const refreshBTN = document.getElementById('refreshBTN');
const warningBTNyes = document.getElementById('warning-button-yes');
const warningBTNno = document.getElementById('warning-button-no');
const playersList = document.getElementById('playersList');
const playersList2 = document.getElementById('playersList2');
const startBTN = document.getElementById('startBTN');
const drawLotsBTN = document.getElementById('drawLotsBTN');

addBTN.addEventListener('click', function() {
  const input = document.getElementById('addPLAYER');
  const person = document.getElementById('addPLAYER').value;
  if (input.value == "") {
    console.log('error_empty_input');
    document.getElementById('errorMSG').style.color = "red";
    document.getElementById('errorMSG').innerHTML = "Please enter a name!";
  } else if (input.value.match(onlyLetters)) {
    console.log('good');
    Players.push(person);
    Players2.push(person);
    playersList.innerHTML = playersList.innerHTML + "<br>" + person;
    document.getElementById('addPLAYER').value = "";
    document.getElementById('errorMSG').style.color = "green";
    document.getElementById('errorMSG').innerHTML = "Success! Add another person.";
  } else {
    console.log('error_input');
    document.getElementById('errorMSG').style.color = "red";
    document.getElementById('errorMSG').innerHTML = "There seems to be an issue with the name format. Please enter letters only!";
  }
});

refreshBTN.addEventListener('click', function() {
  document.getElementById('warning').style.display = "block";
});

warningBTNyes.addEventListener('click', function() {
  location.reload(true);
  document.getElementById('addPLAYER').value = "";
});

warningBTNno.addEventListener('click', function() {
  document.getElementById('warning').style.display = "none";
});

startBTN.addEventListener('click', function() {
  drawLotsBTN.disabled = false;
  const input = document.getElementById('addPLAYER');
  const person = document.getElementById('addPLAYER').value;
  if (input.value == "") {

  } else if (input.value.match(onlyLetters)) {
    console.log('good');
    Players.push(person);
    Players2.push(person);
    playersList.innerHTML = playersList.innerHTML + "<br>" + person;
    document.getElementById('addPLAYER').value = "";
    document.getElementById('errorMSG').style.color = "green";
    document.getElementById('errorMSG').innerHTML = "Success! Let the drawing begin!";
  } else {
    console.log('error_input');
    document.getElementById('errorMSG').style.color = "red";
    document.getElementById('errorMSG').innerHTML = "There seems to be an issue with the name format. Please enter letters only!";
  }
  document.getElementById('addPLAYER').disabled = true;
});

drawLotsBTN.addEventListener('click', function() {
  for (let i = 0; i = Players2.length; i++) {
    if (Players2.length > 0) {
      randomPerson = Math.floor(Math.random() * Players2.length);
      if (randomPerson != Players.indexOf(i)) {
        console.log(Players2[randomPerson]);
        playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players2[randomPerson];
        Players2.splice(randomPerson, 1);
      }
    } else {
      console.log('error_empty_array');
    }
  }
});
<div id="warning" class="warning">
  <div class="warning-flex">
    <h1>All entered names will be deleted</h1>
    <div class="warning-buttons">
      <button id="warning-button-yes" class="warning-button-yes">Yes</button>
      <button id="warning-button-no" class="warning-button no">No</button>
    </div>
  </div>
</div>
<div class="lotteryContainer">
  <div class="left">
    <p>Add a person</p>
    <div class="addPerson">
      <input required id="addPLAYER" type="text">
      <button id="addBTN">+</button>
      <p id="errorMSG"></p>
      <div class="refresh">
        <button id="refreshBTN">Refresh</button>
        <button id="startBTN">Start</button>
      </div>
    </div>

  </div>
  <div class="right">
    <p>Participants</p>
    <div class="tables">
      <div class="tableLeft">
        <p id=playersList></p>
      </div>
      <div class="tableRight">
        <p id="playersList2"></p>
      </div>
    </div>
    <button id="drawLotsBTN">Draw Lots</button>
  </div>
</div>
<script src="app.js"></script>

Answer №1

It seems like your program aims to facilitate a gift-giving scenario among a group of people, similar to a secret Santa exchange. The process involves each person giving and receiving one gift randomly. To achieve this, there is a straightforward algorithm that can be followed:

players = ["Adam", "Bret", "Clay", "Donald"];
players.sort(function(a, b){return 0.5 - Math.random()}); // shuffle the array
gives_to = [...players]; // create a copy of the array values
gives_to.push(gives_to.shift()); // move the first element to the end

In this implementation, the first player in the shuffled list will give a present to the first person in the new order, and so on for the rest of the participants.

Answer №2

After attempting to implement the Trygve Ruud algorithm using a JS script, it seems that the desired functionality is not achieved.

drawLotsBTN.addEventListener('click', function(){
    if(Players.length > 0) {
        console.log(Players)
        Players.sort(function(a, b){
            return 0.5 - Math.random();
        });
        for(let i = 0; i < Players.length; i++){
            playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players[i];
        }
    }
    else{
        console.log('error_empty_array');
    }
    
});

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

How to prevent DataTables from making requests once the table exceeds a certain breakpoint limit

Is there a way to prevent requests from being sent when a table reaches a breakpoint and hides data? Each time the table hides content, it sends a request to the server which can lead to multiple requests. While handling this on the server side is possib ...

Exploring the Concept of Dual Indexing in NumPy

Can you explain how I can assign a matrix to a slice of a slice of a NumPy array? Let's use some sample data and a 1D mask to demonstrate what needs to be done: data = np.array([[1, 2, 11, 21], [2, 4, 12, 23], [3, 6, 13, 25], [4, 8, 14, 27], [5, 10, 1 ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

Efficient method for creating an index in a 2D list from x to y

Currently, I am working on a tic-tac-toe project as part of the Cisco NetAkad course. You can find my progress in this video tutorial: https://www.youtube.com/watch?v=7GDtI9SpGgU. While I completed the game successfully, I deviated from the specified proje ...

Guide on querying a single document in MongoDB that contains a specific value for an element within an array of arrays

I am facing an issue with a document that has an array of arrays and is using embedded documents in MongoDB. The collection name Orders looks like this: "_id" : "HjPGrdkffg7dQPtiX", "ListOrdersResult" : [ { "Orders" : { ...

Issues arise with User obj's utilization of the Instagram API

After setting up my Instagram developer account, I was able to obtain the client_secret and client_id. Authentication went smoothly for my own user (myusername), and I received an access_token. However, when attempting to utilize this endpoint TOKEN] Fo ...

The inner workings of a React.Element object remain concealed during serialization

Here is an example of a functional component: const FuncElement = ({ item }) => { return ( <div className="item-list"> <h1>Items for {item}</h1> <ul> <li>Book</li> <li ...

Modifying the attributes/properties within a class of a bootstrap button

Here is the code that I have: <b-button id="search-button" size="md" class="mt-1 w-100" type="submit" @click="someEvent()" >Example </b-button If we imagine calling someEvent() and wanting to modi ...

picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map. My goal is to be able ...

Launch Internet Explorer and input variable values (such as ScriptEngineMinorVersion)

I am looking to create a script that can open a file and inject values into it. Here is a basic example: Set WshShell = WScript.CreateObject("WScript.Shell") Return = WshShell.Run("iexplore.exe google.com", 1) However, I also need to modify some variab ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog. The example provided on the Angular Material site showcases how to create a dialog: function ...

Monitoring every request in Express.js(logging)

My web application is built on node and express for the backend. With a large number of users, debugging using console logs can be confusing due to messy logs from different users. Is there a way to track logs based on requests (like a Request ID)? ...

Building a flexible array in PHP using checked boxes from the &_POST method for iteration in a foreach loop

I need help with extracting form data from another page and using it as $_POST. The data includes email addresses and file paths stored as checkbox values. My goal is to send an email with attachments for each selected file. I currently have the files in ...

Tips for importing a Multimaterial .dae file in three.js?

I am facing an issue while trying to load a model with multiple materials. I want to access the array of materials but my current approach is not working as expected. loader.load('./dae/tenis.DAE', function ( collada){ dae = collada.scene; ...

Tips for displaying live data in the rows of Element UI's Table

Recently, I've been working with a table that looks like this. <v-table :data="data"> <v-table-column prop="data.attribute" label="Attribute"> </v-table-column> </v-table> Instead of displaying data.attribute in the co ...

Tips for customizing plupload to prompt the user for a file title

I have successfully implemented plupload on my website to allow users to upload photos, and I am also using the jQuery queue widget. My current server method only accepts the filename, chunk, and content of the photo. Is there a way for users to specify a ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

Why React's setState is only returning the last item when a list is saved to a variable

Being a newcomer to React, I am currently working on a small project that involves using the GitHub API to perform a search and display the results on the screen via AJAX. Right now, I am utilizing a for loop to iterate through the response data, saving it ...