JavaScript Nested Array Looping Script

I am currently working on a loop script for my application that checks for the full capacity of a user array and adds a user ID if there is space available.

The data in my JSON file is structured around MongoDB and contains 24 entries (hours). Each entry includes a mins array (as shown below).

I have attempted to use the script below, but it needs to evaluate each array individually based on the min value.

const hour = await db.Timer.findOne({hour: time[1]}) // finding the hour in the database
const timer = await db.Timer.findOne({hour: time[1]}, { mins: {"$elemMatch": {min: time[2]}}}) // locating a specific minute
let maxUsers = 3
for(let i = 0; i < hour.mins[i].users.length; i++) {
    if(hour.mins[i].users.length < maxUsers){
      console.log(i)
    } 
}

hour and timer are arrays that can be accessed using time[1] (hour) and time[2] (minute). This is the information I need to work with.

// sample 'mins' array structure
[
  {
    users: [ 432143, 543254, 6545423 ],
    min: 21
  },
  {
    users: [ 3421, 432143, 43213 ],
    min: 22
  },
  { users: [ 7735 ], min: 23 },
  { users: [], min: 20 }
]

// 'hour' output
{
  hour: 15,
  mins: [
    { users: [Array], min: 21 },
    { users: [Array], min: 22 },
    { users: [Array], min: 23 },
    { users: [], min: 20 }
  ]
}

// 'timer' output
{
  mins: [ { users: [Array], min: 21 } ]
}

I would appreciate any suggestions on how to assess the arrays based on the minute value.

Answer №1

For those looking for a resolution.

This is the method I used to solve the issue:

let myTime = clock.minutes
      const people = myTime.filter(myTime => myTime.users.length < 3 && myTime.minutes > time[2]);
      console.log(people[0].minutes)

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

Is there a way to transform the SmartyStreets' jQuery.LiveAddress plugin into its JavaScript SDK?

My website currently utilizes the jQuery.LiveAddress plugin, however, it was deprecated and subsequently removed by SmartyStreets back in 2014. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <s ...

Strategies for Implementing Multi-Step Password Form Validation

Currently, I am using https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps as the foundation of my form with some adjustments. Validation is functioning correctly where empty fields disable the next button. However, when I attempt to add ...

Conflicts between Bootstrap Validator and Ajax.BeginForm in Partial Views of MVC

My current issue involves using Ajax.BeginForm to post data on a form without refreshing the entire page. The goal is to validate a textbox - if it has a value, then the data should be posted; otherwise, a validation message should be displayed. However, I ...

Error: The object with the memory address 0x7f3f4bd01470 returned by the neo4j.work.result.Result is not compatible with JSON serialization

Hello, I am facing an error with the following code and need assistance in resolving it: class GenerateQuery: @staticmethod def get_nlg(graph_query): # graph = Graph("http://localhost:7474",auth=("neo4j", "pass" ...

unable to retrieve an object's property

Currently, I am implementing a JWT token compare function to authenticate user login by comparing the user password. However, I am facing an issue where I cannot access the user password after executing the mongoose query. exports.login = async(req, res, n ...

Determine which keys in the req.body object exist within the specified schema in Node.js

How can I extract the values from a POST request that match the keys present in my model's schema? For instance, if my 'user' model includes 'name' and 'email' keys, I only want to retrieve data for these fields as I loop ...

"Supporting Python object serialization into JSON with the ability to choose specific attributes

I am having trouble converting my object to and from JSON. Because this object utilizes SQL Alchemy, the regular json.dumps(vars(self)) method is ineffective. I am in search of the correct syntax to achieve this task. def to_json(self): obj = ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

Encountered an issue while trying to import JSON data into elastic using logstash

Having recently ventured into the realm of ELK stack, I find myself challenged with the task of importing single line JSON files to Elasticsearch using Logstach. Despite my efforts, nothing seems to appear at Elasticsearch (10.10.20.13:9200/monitor/_search ...

Is there a way to simulate a middle mouse click using Selenium and JavaScript?

I am looking to simulate a middle button mouse click on a text URL within a webpage using Selenium code in JavaScript so that it opens in a new tab. Here's an example: await driver.get("https://google.com"); // This is the xpath for the &a ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

The issue of Bootstrap dynamic tabs retaining their active state even after switching tabs, leading to elements being stacked

For my university project, I am developing a website that resembles a text editor using Bootstrap as the framework. To create the website menus, dynamic tabs have been utilized. The following is the code snippet I have implemented: <!--Bootstrap ...

"Interrogating the Use of Question Marks in Meta Tags for Social Web Crawlers with an AngularJS App and Prerender.io

I am facing an issue with my website's meta tags that contain Japanese characters for the Open Graph protocol. Despite setting everything correctly, they appear as question marks when using a crawler tool like Facebook's debugger at https://devel ...

What is the best way to close an ajax page within the main page using a button?

I am dealing with a situation where I have 2 pages. The first page contains a div called 'ajaxicall', which loads another page inside it. The challenge I am facing is figuring out how to close the second page when I click on the "close" button w ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causi ...

What is the best way to verify if a value matches the container ID in Vue?

I am trying to create a condition where a property is checked against the ID of a div container. If they match, I want to display the container. For example, in the code snippet below, I need to compare the activeWindow property with the div id. If they a ...

Using Array.Map() to retrieve the child array within a React component

Here is the data I have retrieved from an API: [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", ...

Employ LINQ to retrieve data from XML and store it in an array by using the .ToArray()

Transitioning from VB6 to VB.NET, I am working on configuring an app using XML files for more than just basic settings. I aim to extract elements from a single XML node in the file and convert them into an array of strings. Despite finding examples of sim ...

Using PHP and JavaScript to determine device screen width and eliminate the $_GET parameters from the URL

I have implemented the following JavaScript code to detect screen width and utilize it as a constant throughout my template files using conditional statements to control the visibility of different sections on my site. Just to clarify, I am working within ...