Monitor the user's attendance by utilizing two separate for loops

I'm currently developing an angularjs attendance tracking system and I'm facing challenges when it comes to accurately counting the number of days an employee is absent. Despite attempting to solve this issue with two nested for loops, I am still encountering inconsistencies in the count of absent values.

For instance

The variable days.length encompasses a range of 30 days from 11-1-17 - 11-30-17

getDaysInMonth(10, 2017);

function getDaysInMonth(month, year) {

  var date = new Date(year, month, 1);


  console.log('month', month, 'date.getMonth()', date.getMonth());

  while (date.getMonth() === month) {
    days.push(moment(date).format('MM-DD-YYYY'));
    date.setDate(date.getDate() + 1);
  }

  return days;

}

The array objArray contains 4 distinct dates:

11-27-2017, 11-28-2017, 11-29-2017, 11-30-2017

Controller Implementation (using for loop)

for (var y = 0; y < days.length; y++) {
    for (var z = 0; z < objArray.length; z++) {
      if (days[y] === moment(objArray[z].day).format('MM-DD-YYYY')) {
        console.log('entry found', days[y]);
      } else {
        console.log('absent'); // generating multiple entries
      }
    }
  }

Modification

Adjusted objArray values

objArray: [
  {
    day: "2017-11-26"
  },
  {
    day: "2017-11-27"
  },
  {
    day: "2017-11-28"
  }
]

Answer №1

When objArray is already a string array, you can skip the inner loop entirely

for (var y = 0; y < days.length; y++) {
      if ( objArray.indexOf(days[y]) != -1 ) { //use index of instead of comparing individual values
        console.log('exist', days[y]);
      } else {
        console.log('absent'); 
      }
 }

Alternatively, you can do this:

days.forEach(function(day) {
  console.log(day, (objArray.indexOf(day) != -1) ? "exist " + day : "absent");
})

Update

Prior to comparison, convert objArray into a string array

objArray = objArray.map( function(item){
   item = item.day.split("-");
   return item[1] + "-" + item[2] + "-" + item[0].slice(-2)
})

Example

var days = ["11-1-17", "11-2-17", "11-3-17", "11-4-17", "11-5-17", "11-6-17", "11-7-17", "11-8-17", "11-9-17", "11-10-17", "11-11-17", "11-12-17", "11-13-17", "11-14-17", "11-15-17", "11-16-17", "11-17-17", "11-18-17", "11-19-17", "11-20-17", "11-21-17", "11-22-17", "11-23-17", "11-24-17", "11-25-17", "11-26-17", "11-27-17", "11-28-17", "11-29-17", "11-30-17" ];

var objArray = [ { day: "2017-11-26" }, { day: "2017-11-27" }, { day: "2017-11-28" } ];

objArray = objArray.map( function(item){
   item = item.day.split("-");
   return item[1] + "-" + item[2] + "-" + item[0].slice(-2)
})

days.forEach(function(day) {
  console.log(day, (objArray.indexOf(day) != -1) ? "exist " + day : "absent");
})

Answer №2

The issue lies with the nested loop which is generating excess output. Furthermore, if there are string values such as "11-30-2017" in your objArray, it will lead to an error.

moment(objArray[z].day) resolves to moment(undefined) Consequently, you will consistently receive a moment object reflecting the current date only.

To rectify your printing statement, consider implementing flags for clarity.

var exist;
for( condition of outer loop )
{
   exist = false;
  for( condition of inner loop ){
  if( specific condition ){
     exist = true;
     break;
   }
 }
  //Evaluate flag and display presence/absence status
}

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

No files located by the server

My experience with writing a basic express script to serve a webpage with embedded Javascript has been quite frustrating. The server seems to struggle finding the files I provide, and what's even more aggravating is that it sometimes works but then su ...

Sending variables to other parts of the application within stateless functional components

My main component is Productos and I also have a child component called EditarProductos. My goal is to pass the producto.id value from Productos to EditarProductos. Here is my Productos component code: import {Button, TableHead, TableRow, TableCell, Tabl ...

Distinguishing a button based on its class

I am currently designing a website to showcase personalized store products. Each product info box includes a button, as shown in the screenshot below: https://i.sstatic.net/hiXiY.png Upon clicking on the "Options" button, users can view information about ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

What is the best method for sending a PHP variable to an AJAX request?

I am working with three files - my main PHP file, functions.php, and my JS file. My challenge is to pass a PHP variable to JavaScript. Below is a snippet from my MAIN PHP FILE: function ccss_show_tag_recipes() { //PHP code here } Next, here's t ...

Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encounterin ...

Navigating through HTML content and extracting specific elements

After using an ajax call to retrieve the partialView HTML of a page, I need to extract information from the main div before displaying it. This data specifically relates to the size information in order to create a floating window. Here is the code snippe ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

Ensuring the validity of a signed cookie in Node using Express

I'm currently working on incorporating signed cookies in Node's express module. I've reviewed the documentation, but I'm struggling to understand how to properly verify them. My understanding is that verification must occur on the serve ...

The application threw an error stating that Angular JS is not a function, causing it to be

I've encountered an issue where including angular scripts (such as Controller.js) in the angular view does not work - resulting in a "not a function, got undefined" error. However, when I add these scripts in the main view, it works perfectly fine. Do ...

After refreshing the page, the data stored in the localStorage array gets replaced

After refreshing the webpage, my localStorage array values are being overwritten. During a session, I am able to update values on the front end, and the array in localStorage gets updated accordingly. However, if multiple inputs are changed during a sessio ...

Determining Field of View (FOV) for a perspective camera in ThreeJS following a browser window resize

After changing the size of the browser window, I'm trying to determine the correct Three.JS camera FOV. I have looked at several related questions, but haven't found a solution yet: How to calculate fov for the Perspective camera in three js? C ...

Improper Alignment of Bootstrap 4 Navbar Link: Troubleshooting Required

Take a look at the image for the issue: https://i.stack.imgur.com/u9aCy.png As shown in the image, the NavBar links are stacked instead of being displayed in one row. This is the HTML code I have used: <!doctype html> <html> <head> ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

JavaScript - AJAX Call Terminated after a Period on Secure Socket Layer (SSL)

Currently, my AJAX calls over an SSL connection using the Prototype JS framework run smoothly initially. However, after 10 seconds of being live on the page, they start failing with a status of 0 or 'canceled' in the Network Inspector... This is ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

Leveraging a unique JavaScript function in AngularJS from a separate controller or directive

I am currently working on a JavaScript file named 'linechart.js' which functions as a library. Inside this file, there is an object that contains a function responsible for generating a line chart using D3 when provided with some data. The code s ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

Hold off on moving forward until the content has been loaded using ajax within loops

I am facing an issue with waiting for ajax requests to complete before proceeding. My task involves iterating through all the options in five select lists. Upon selecting an option in "Select1", it dynamically loads or refreshes "Select2". The same proces ...