Setting values for array elements using a loop

Struggling to implement the loop function on an array, I am seeking assistance. My goal is to assign people's requests to groups based on vacancies in those groups automatically.
Therefore, I envision a table like this:
Group 1 | Number of People
Group 2 | Number of People
Group 3 | Number of People
and so forth...

To achieve this, I understand that I need an "if" condition to compare reservation requests with group vacancies and then make the assignment if the vacancy exceeds the request.
I can add the reservation variable to an array using the array.push function but I'm facing challenges in looping through and assigning values to a two-column array...

<label for="groups">Reservation request (1-10):</label>
<div id="reservation">
<input type="number" name="form" id="number" min="1" max='10'>
<br><br>
<button onclick="groups()">Submit</button>
</div>

var myArray = ["Group 1", "Group 2", "Group 3"];
function groups() {
    form = number.value;
    if (form >=1){  
        for (var i; i<myArray.length; i++) {
            if (myArray[i] > form){
                myArray[i] = form;
                console.log(myArray);
            }
            else {alert("no");}
        }
    }

Can anyone offer guidance?

Thank you, Marion

Answer №1

If my understanding is correct, your goal is to:

  • Begin with a list of empty groups that can expand by adding people but should not exceed 10 members
  • Upon request (button press), add any number of people to the first group capable of accommodating all requested members
  • If no group can accommodate all requested members, create a new group and assign the request to it

To achieve this, it is recommended to avoid using multi-dimensional arrays ("arrays with two columns"):

var myArray = [0, 0, 0];

function groups() {
    var form = document.getElementById('number').value;
    if (form >= 1) {  
        for (var i; i<myArray.length; i++) {
            if (myArray[i] < 10 - form) {
                myArray[i] += form;
                return;
            }
        }
        myArray.push(form); // this will only occur if the "return" statement above never happened
    } else {
        alert("no");
    }
}

If you prefer to use group names / a multi-dimensional array, you can implement it like this:

var myArray = [['Group 0', 0], ['Group 1', 0], ['Group 2', 0]];

function groups() {
    var form = document.getElementById('number').value;
    if (form >= 1) {  
        for (var i; i<myArray.length; i++) {
            if (myArray[i][1] < 10 - form) {
                myArray[i][1] += form;
                return;
            }
        }
        myArray.push(['Group ' + myArray.length, form]); // this will only happen if the "return" statement above never occurred
    } else {
        alert("no");
    }
}

For improved clarity, you can utilize structured objects within myArray instead of additional arrays:

var myArray = [{name:'Group 0', reserved:0}, {name:'Group 1', reserved:0}, {name:'Group 2', reserved:0}];

function groups() {
    var form = document.getElementById('number').value;
    if (form >= 1) {  
        for (var i; i<myArray.length; i++) {
            if (myArray[i].reserved < 10 - form) {
                myArray[i].reserved += form;
                return;
            }
        }
        myArray.push({name:'Group ' + myArray.length, reserved:form}); // this will only occur if the "return" statement above never happened
    } else {
        alert("no");
    }
}

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

Adding elements to an array appears to cause the previously created object to react

I am encountering a situation where once I add an object to an array, it becomes reactive to any changes made. // actions.js export const addToCart = ({ commit }) => { commit('addToCart'); // successfully updates the state setTimeout ...

Retrieve the file path of the local system's home directory from the server

The server is up and running, I am looking to retrieve the file path of the local system in which the AWS server is operating using Node.js. ...

"Comparing the use of a hashmap versus an array of arrays in this specific

Hey there, working with C programming language and have a question I'd like to discuss. So, let's say we have data structures structured this way: typedef struct { char* tag; char* name; unsigned int id; } object; In some other lang ...

Bootstrap Datepicker allows you to set a maxdate of 2 days from the initial date selected

Imagine this scenario: when I choose a date for Check-In on May 10th, I want the Check-Out section to automatically show May 10th selected as well, with the following 2 days available and the rest disabled. If you're looking for documentation, you ca ...

Displaying an alert box once the form has been submitted

I have created a form in asp.net mvc and I am looking to display an alert message when the user submits the form. public ActionResult AddMessage(Message message) { If(ModelState.IsValid) { db.Messages.Add(message); ...

How to use TypeScript to filter arrays with multiple dimensions

I've been attempting to filter an array with multiple filters, but I can't seem to achieve the desired outcome so far. This is my Angular component: list = [ {type: type1, code: code1}, {type: type2, code: code2}] searchElement(code?: string, ...

Creating Uniform Heights Across Devices with Responsive Design Strategies

I am struggling with a height consistency issue that I cannot figure out. The problem can be seen in this Fiddle: FIDDLE Here is the code snippet: $(document).ready(function() { if ($(window).width() > 768) { $(window).ready(function() { ...

Developing an interactive input field using JavaScript's Document Object Model (DOM)

I am struggling with creating an editable text field using JavaScript. I have come across a function that allows for editing, but I am unsure if it is possible to change the title from High School to Middle School, which is generated by the function create ...

Is there a way to modify the value of a JavaScript object?

My React componentwillmount fetches data from an ExpressJS API using Axios and receives a JSON response, which is then converted to an object by Axios. [{"client_nick":"PlayTalk","connected_time_record":183710127},{"client_nick":"PlayTalk","connected_time ...

Develop a unique splitter code that utilizes pure javascript and css, allowing users to drag and drop with precision

I am facing an issue with setting the cursor above my drop panel, as it results in a flicker effect. How can I set the cursor for my example to work properly? I have tried multiple different approaches to make this work. Although I am using the provided ...

How can I make rows appear dynamically when the user clicks a button?

I am trying to add rows dynamically when the user clicks on a button. I have created a script for this purpose, but unfortunately, it is not working as expected. Can someone please assist me with fixing it? <script> var i; i = 2; function AddR ...

Updating the appearance of input fields without hiding them using display:none

One innovative approach to modifying a standard input is to utilize the display:none property on the input element, while adding a customized background-image to its corresponding label. CSS: input[type="checkbox"] { display: none; } input[type="checkb ...

Steps for generating an array entry containing an ObjectId and a Number

I am a newbie when it comes to mongodb and I am attempting to create an entry like this: { "resources": [ { "amount": 1, "resource": { "_id": "61be82b9549b4ede ...

Need to know how to connect to a private Google Calendar using NodeJS?

While attempting to access a private Google Calendar through the use of the NodeJS Google API package, I encountered an error stating "Error: Not Found": Error: Not Found at createError (/Users/devacc/myproject/node_modules/axios/lib/core/createError. ...

Configuring the HTTP Header to authenticate with a DRM license server using Tizen's AVPlay

I am trying to use AVPlay for playing DRM-protected content, but I'm facing an issue with setting a custom HTTP header for the license URL. Can anyone guide me on how to achieve this? webapis.avplay.setDrm('PLAYREADY', 'SetProperties&a ...

Groupings of pairs stored in either Tuples or ArrayLists

I am currently struggling with creating a list of pairs, and it's proving to be quite challenging. Just a quick note: I am aware that there will be duplicates in the list, but they are not a concern for me. For instance, if I define $b = @{"dog" = ...

What is the process for utilizing the cin function to read character data, store it in an array, and subsequently

I've run into a problem with my simple console application. It's supposed to read 3 words and store them in an array, but for some reason, it only displays the third word three times on the console. For example, if I input "one", "two" and "three ...

Toggling the visibility of divs in a dynamic layout

How can I use JQuery/JavaScript to show only the comment form for a specific post when a button or link is clicked on a page containing multiple posts divs with hidden comment forms? <div class="post"> <p>Some Content</p> <a ...

Displaying an array of floating-point numbers with a size determined by the user's input

I'm struggling with a homework assignment that involves inputting real numbers into an array of size 20 and printing them as floats with one decimal place. The problem is, my array is printing more than the required five numbers: 10, 37, 15, 21, 18. ...

Problems encountered when transferring information from jQuery to PHP through .ajax request

Hey there! I am currently working with Yii and facing an issue while trying to pass some data to a controller method called events. This is how my jQuery ajax call looks like: var objectToSend = { "categories" : [selectedOption],"datefrom" : month + "" + ...