Is it possible to iterate and add an array to another array using a loop?

Looking for a more efficient way to organize my code using loops

let tmpD = [];
let tmpS = [[], [], []];

for(let i = 0; i < tmpD.length; i++) {
  signed = doctors.doc(tmpD[i].key).collection('schedule').get();
  signed.then(function(ss){
    ss.forEach(function(schedule){
      tmpS[i].push(schedule.data());
    });
    console.log(tmpS[i]);
  });
}

I attempted to use a for loop above the first signed statement and push data accordingly, but ended up with all data in a single array. I also tried pushing the data to tmpS[i] directly, resulting in an error.

Answer №1

To efficiently manage the data, one approach is to create a 2D array consisting of variables like tmpS0, tmpS1, and so on. These arrays can then be updated based on their respective indices:

let tmpD = [];
let tmpS0 = [];
let tmpS1 = [];
let tmpS2 = [];

let tmps = [tmpS0, tmpS1, tmpS2];

tmpD.forEach(({ key }, i) => {
  const signed = doctors.doc(key).collection('schedule').get();
  signed.then(function(ss) {
    ss.forEach(function(schedule) {
      tmps[i].push(schedule.data());
    });
    console.log(tmps[i])
  });
})

An Update has been made:

If there is a need for dynamic variables, you can simply work with a single tmpS array and continue adding data to it based on the index from the tmpD array:

let tmpD = [];
let tmpS = []; // This acts as a 2D array

tmpD.forEach(({ key }, i) => {
  const signed = doctors.doc(key).collection('schedule').get();
  signed.then(function(ss) {
    tmpS[i] = tmpS[i] || []; // Initializing the inner arrays if needed

    ss.forEach(function(schedule) {
      tmpS[i].push(schedule.data());
    });

    console.log(tmpS[i])
  });
})

// The tmpS array will have inner arrays equivalent to the length of tmpD
console.log(tmpS)

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

React - retrieving the previous page's path after clicking the browser's "back" button

Imagine I'm on Page X(/path-x) and then navigate to page Y(/path-y). Later, when I click the "back" button in the browser. So my question is, how do I retrieve the value of /path-y in PageX.tsx? Note: I am utilizing react-router-dom ...

The array is coming back empty after attempting to add objects to it

My Node JS and Express JS controller code is below: const UserComment = require(".../model/UserComment"); router.post("/get/comments", async (req, res) =>{ try{ let currentUserID = req.body.userID; let myUserComment = await UserComment.find({userID: cu ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

Implementing a tracking mechanism

My goal is to incorporate a counter into this feature. When a number is clicked, the message should read "You've selected 1 out of 5," indicating that the user needs to choose 5 numbers. If the same number is clicked again, it should deselect and reve ...

Incorporating Angular module into the mean.io bundle

Need help with adding the angular-ui-grid module to a mean.io package: $ cd packages/custom/mypackage $ npm install angular-ui-grid --save To import the JS, add this line to packages/custom/mypackage/public/index.js: import 'angular-ui-grid'; ...

What is the best way to transform a JS const into TSX within a Next.js application?

Exploring the code in a captivating project on GitHub has been quite an adventure. The project, located at https://github.com/MaximeHeckel/linear-vaporwave-react-three-fiber, showcases a 3D next.js application that enables 3D rendering and animation of mes ...

Adjusting ArrowHelper Width in Three.jsLooking to change the size of an Arrow

I have been attempting to adjust the width of pink lines on this jsfiddle link: animation of object In my code, I am defining local basis vectors as follows: // Defining local vector axis of plane var thetadir = new THREE.Vector3(1, 0, 0); var phidir = ...

Allow the submission button to be activated only when both the FromDate and ToDate have been

I am looking to activate the submit button once both the FromDate and ToDate fields are selected. In my scenario, all form fields must be filled out in order to enable the submit button. $('#myform > input').on('input', function ...

Retrieving the ID and value of a specific dropdown list using jQuery from an array of dropdown lists

My HTML structure looks like this: <?php foreach($active_brand as $brand) { ?> <select name="selector" id="selector"> <?php foreach($options as $option) { ?> <option <?php if($brand['State'] == $option) { ?& ...

Program for sending and receiving messages

The concept behind this program is to enable users to send messages. The user navigates to the web interface, selects their ID as the sender and chooses a receiver ID before pressing submit. Upon submission, they are directed to a page displaying all the m ...

Pass along a JSON array from Express to Angular2

I have been working on sending a custom array filled with mongoose errors, and I am successfully creating the array. Below is the code snippet: student.save(function(err, student) { if(err) var errors = []; for (field in err.errors) { ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Dynamic way to update the focus color of a select menu based on the model value in AngularJS

I am looking to customize the focus color of a select menu based on a model value. For example, when I choose "Product Manager", the background color changes to blue upon focusing. However, I want to alter this background color dynamically depending on th ...

What is the maximum size a key can be for an array in PHP?

When creating associative arrays, I am concatenating strings from 1 to n columns as the key value. Should I be concerned about a maximum length for keys causing issues in the future? If there is a limit, I may need to reconsider my approach. ...

The Node/Express Rest API appears to keep directing requests to the same controller function, despite the mappings being correctly

Currently, I am in the process of developing a node/express REST API. When making requests to the following endpoints: http://localhost:5000/api/news and http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80 I noticed that both URLs trigger the same ...

Can a function call in C be written on a single line with an array of strings or integers as a parameter?

Consider these two functions : void my_function1(char ** params, int size) { for (int i=0; i<size; i++) printf("%s \n",params[i]); } void my_function2(int * values, int size) { for (int i=0; i<size; i++) printf("%d \n",values[i]); ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

JavaScript text spacing

I'm currently utilizing the JavaScript code snippet below to clear out the existing content within a div element in order to insert new elements. However, I've encountered an issue where once the div is cleared, its CSS styling is lost. I am atte ...

I'm having trouble getting my Ajax edit code to function correctly. Can anyone offer some assistance?

I am currently working on a basic registration system that includes two forms: one for registration and another for selecting a city. I have encountered an issue where newly added cities update perfectly, but when trying to use the selected city in the reg ...

Is it time to test the functionality of arsort() in our code?

It appears that the order in which arsort produces results plays a critical role in a large and complex codebase. Instead of delving into dissecting what's happening across approximately 50 classes, is there a straightforward method to shuffle items w ...