Discover the absent day in an array of dates using JavaScript

Upon receiving an array of day dates from an API, the following structure is observed:

0:{date: "2016-11-17T00:00:00",…}
1:{date: "2016-11-18T00:00:00",…}
2:{date: "2016-11-19T00:00:00",…}
3:{date: "2016-11-21T00:00:00",…}
4:{date: "2016-11-22T00:00:00",…}
5:{date: "2016-11-23T00:00:00",…}

In this particular instance, a date seems to be absent from the array:

{date: "2016-11-20T00:00:00",…}

What would be the most effective method in order to identify a missing day within an array of dates using Javascript or Angular?

This information may prove valuable when configuring a datepicker by setting disabled days accordingly.

Answer №1

Take a look at this solution:

  1. To start, ensure the array is sorted using Array.prototype.sort

  2. Next, utilize Array.prototype.reduce along with a hash table to identify any missing dates

See the demonstration provided in the snippet below:

var array=[
  {date:"2016-11-17T00:00:00"},
  {date:"2016-11-19T00:00:00"},
  {date:"2016-11-18T00:00:00"},
  {date:"2016-11-21T00:00:00"},
  {date:"2016-11-22T00:00:00"},
  {date:"2016-11-23T00:00:00"},
  {date:"2016-11-27T00:00:00"}
];

var result = array.sort(function(a,b){
   return Date.parse(a.date) - Date.parse(b.date);
}).reduce(function(hash){
  return function(p,c){
    var missingDaysNo = (Date.parse(c.date) - hash.prev) / (1000 * 3600 * 24);
    if(hash.prev && missingDaysNo > 1) {
      for(var i=1;i<missingDaysNo;i++)
        p.push(new Date(hash.prev+i*(1000 * 3600 * 24)));
    }
    hash.prev = Date.parse(c.date);
    return p;
  };
}(Object.create(null)),[]);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Answer №2

Initialize a new array called missingDates[]

Go through each element in the provided array by using a for loop

for (i = 0; i < array.length; i++){
    var date1 = convert the element at index i in the array to a date
    var date2 = convert the element at index i + 1 in the array to a date (keeping in mind that index i + 1 should not exceed array.length)

    //calculate the number of days between the two dates, if it is greater than 1, then there is a missing date
    var missingDate = create the missing date by adding one day to your date1 variable

    //add the missingDate to the missingDates[] array
    missingDates.push(missingDate)
}

Answer №3

To determine a missing date, you can create a method called getMissingDate. This method will return null if there is no missing date, or it will return the corresponding Date object if there is a gap of more than one day between two dates:

var arr1 = [{date: "2016-11-17T00:00:00"}, {date: "2016-11-18T00:00:00"}, {date: "2016-11-19T00:00:00"}, {date: "2016-11-21T00:00:00"}, {date: "2016-11-22T00:00:00"}, {date: "2016-11-23T00:00:00"}],
    arr2 = [{date: "2016-11-17T00:00:00"}, {date: "2016-11-18T00:00:00"}, {date: "2016-11-19T00:00:00"}, {date: "2016-11-20T00:00:00"}, {date: "2016-11-21T00:00:00"}, {date: "2016-11-22T00:00:00"}, {date: "2016-11-23T00:00:00"}],
    getMissingDate = function(arr) {
      var result = null;
      for (var i = 0, l = arr.length - 1; i < l; i++) {
        var current = new Date(arr[i].date),
            next = new Date(arr[i + 1].date);

        if (1 < Math.ceil(Math.abs(next.getTime() - current.getTime()) / (1000 * 3600 * 24))) {
          result = new Date(current.setDate(current.getDate() + 1));
          break;
        } 
      }

      return result;
    };

console.log('arr1:', getMissingDate(arr1));
console.log('arr2:', getMissingDate(arr2));

Answer №4

var data=[
  {timestamp:"2016-01-01T00:00:00"},
  {timestamp:"2016-03-01T00:00:00"},
  {timestamp:"2016-04-01T00:00:00"},
  {timestamp:"2016-07-01T00:00:00"},
  {timestamp:"2016-09-01T00:00:00"},
  {timestamp:"2016-11-01T00:00:00"},
  {timestamp:"2016-12-01T00:00:00"}
];

var sortedData = data.sort(function(a,b){
   return Date.parse(a.timestamp) - Date.parse(b.timestamp);
}).reduce(function(hash){
  return function(previous, current){
    var missingDaysNo= (Date.parse(current.timestamp) - hash.prev) / (1000 * 3600 * 24);
    if(hash.prev && missingDaysNo > 1) {
      for(var i=1; i<missingDaysNo; i++)
        previous.push(new Date(hash.prev+i*(1000 * 3600 * 24)));
    }
    hash.prev = Date.parse(current.timestamp);
    return previous;
  };
}(Object.create(null)),[]);

console.log(sortedData);
.as-console-wrapper{top:0;max-height:100%!important;}

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

Dragging the mouse outside of an element after clicking inside

I've come across a common issue, but unfortunately haven't been able to find a solution yet. window.onload = function (e) { var foo = document.getElementById('foo'); foo.addEventListener('click', function(e) { ...

Tips for implementing autocomplete with tags in Jquery

I have a drop-down with autocomplete functionality, and I am attempting to add tags to the list. When I populate the availableTags array and run the project, everything works fine. File.JS var availableTags = []; $(document).ready(function(){ $(function() ...

Aligning images with absolute CSS to text that is wrapping positions the images perfectly alongside the text content

My webpage has a long content section that resizes based on the browser width. Here's an example: <h1 id="loc1">Title</h1> <p>bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bodycopy bod ...

What is the best way to establish my permit requirements on a monthly basis?

An employee is only allowed to request up to 3 permits per month. If they need a fourth permit, they will have to wait until the following month. Here is my table structure for permissions: Permissions id (integer), format (text), date_r ...

Erase every element contained within the div

What steps should I take to clear out the elements within my mainDiv? <div id='mainDiv'> <fieldset> <div> <input type='text'> <select></select> </div> ...

Problem with animated scrolling in Jquery

Currently, I am working on a function that aims to smoothly scroll the web to a specific div each time a user scrolls "into" a container div. You can get a better idea of what I mean by looking at my JSFiddle. Everything works perfectly when the user scro ...

The pdf2json encountered an error when attempting to process a PDF file sent via an HTTP

I am encountering an issue while attempting to extract information from PDF files using a nodejs script. Upon running the program, I encounter the following error: Error: stream must have data at error (eval at <anonymous> (/Users/.../node_modules/ ...

I am looking to merge two tables in MySQL using a many-to-one relationship and retrieve a customized JSON output similar to the example provided below. How can this

How can I perform a MySQL join on two tables (many to one) and generate a specific JSON output as demonstrated below? Note: Please do not label this as a duplicate. Although there is a similar previous question posted, there are distinct differences that ...

Loading a different webpage seamlessly without having to reload the current one

Here is a snippet of my code in okay.html: {% extends "sch/base.html" %} {% load staticfiles %} {% block content %} <div class="row" id="ada"> <form action="" method="post> {% csrf_token %} <div align="center" class="cont ...

Transforming HTML with JavaScript

I am facing a challenge in my JavaScript application where I receive HTML code from an endpoint that contains radio buttons. Unfortunately, I cannot modify the HTML content coming from this endpoint. My goal is to convert these radio buttons into regular b ...

Getting the value of a sibling select element when a button is clicked

Trying to retrieve the selected option value on button click has become a challenge due to multiple groups of buttons and select elements. The key seems to be using siblings somehow, but the exact method remains elusive... <div class="form-group" ng-re ...

Enhance the functionality of the 'validate as true' function

I have an object that resembles the following $scope.object = { Title: 'A title', Status: 'Open', Responsible: 'John Doe', Author: 'Jane Doe', Description: 'lorem ipsum dolor sit' } My aim now i ...

I am currently struggling to make the userID route parameter function correctly with react-router-relay

I've been diving into the world of React Relay and GraphQL with react-relay-router, but I'm having trouble getting the params in my routes to function correctly. Specifically, I'm struggling with the "/Maps/:userID" route. Let me share my r ...

Using VueJs and BootstrapVue, you can easily set up a table to delete items only on the

I have set up a page showcasing all my items in a BootstrapVue b-table. Each item has the option to be deleted. However, I encountered an unexpected issue when I enabled pagination using the b-pagination element and :per-page attribute. The problem arises ...

Forward user to a new page following successful login utilizing angular.js router and PHP

I am in need of assistance. I am looking to implement a page redirection after a user logs in using Angular.js with PHP as the backend. I have written some code, but it seems to be not functioning correctly. Below is an explanation of my code. index.htm ...

Display the current time and continuously update it in real-time on the DOM using React

Incorporating a live clock feature into my app is important to me. I want the time to update automatically, without requiring the user to manually refresh the page. My goal is to have a clock display the time, for example 11:59, and then transition to 12: ...

Geoserver does not have the 'Access-Control-Allow-Origin' header

map.on('singleclick', function (evt) { document.getElementById('info').innerHTML = "Looks like you need to redo this :) !!!"; var view = map.getView(); var viewResolution = view.getResolution(); var source = hcm.getSource(); var url = s ...

How can one check in JavaScript if a specific URL was targeted with a XMLHttpRequest?

While I am familiar with monitoring network traffic in the browser's development tools and having XMLHttpRequests shown in the console, I am curious if there is a specific window property that showcases all network activity at once? ...

Typescript conversion: Changing a relational array into a tree object

My database is structured as an array of objects with the following format; array = [ {"name": "a", "id": "1", "parentId": NULL}, {"name": "b", "id": "2", "parentId": "1"}, {"name": "c", "id": "3", "parentId": "1"}, {"name": "d", "id": "4", "parentId" ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...