Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task.

Here is a snippet of my datoArray:

["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10"]

and so on...

Below is the logic I am attempting to apply:

for(var i = 0; i < this.datoArray.length; i++){
    this.skoleAar = parseInt(this.datoArray[i].slice(0,4))
    this.skoleMaaned = parseInt(this.datoArray[i].slice(5,8))
    this.skoleDag = parseInt(this.datoArray[i].slice(8,10))

        if(this.skoleAar < currentYear){
            this.datoArray.splice(i, 1);
        }
        if(this.skoleAar == currentYear && this.skoleMaaned < currentMonth){
            this.datoArray.splice(i, 1);
        }
        if(this.skoleAar == currentYear && this.skoleMaaned == currentMonth && this.skoleDag < currentDay){
            this.datoArray.splice(i, 1);
        }
    }

The variables, `currentYear`, `currentMonth`, and `currentDay` are obtained from another function. When logged, they show integer values like 2016 for the year and 8 for the month when extracted from the start of the array. For `currentYear`, `currentMonth`, and `currentDay`, it displays 2016, 11, 20 respectively, representing today's year, month, and day all as integers. However, despite these comparisons of integer values, the conditions inside the "if" statements do not seem to work as expected. It appears there may be an issue with the way I am performing the comparisons. As far as I understand, this should be the correct way to compare integer values, so I am puzzled as to why the logic is failing?

Answer №1

To filter dates in ISO-8601 format, you can utilize the Date.parse() method.

var dates = ["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10", "2016-12-15"];

function excludePreviousDates(data) {
  var today = new Date();
  console.log('Initial state: ' + data);
  var updated = dates.filter(function(dateString) {
    return Date.parse(dateString) >= today;
  });
  console.log('Final state: ' + updated);
  return updated;
}

var filteredDates = excludePreviousDates(dates);

Answer №2

It appears that your date values are in compliance with RFC standards, which means they can be directly used in a new Date object. To filter these dates based on their relation to the current date, you can compare them to today:

var today = new Date()
var futureDates = this.datoArray.filter(d => new Date(d) >= today)

(for pre-ECMA6:)

var today = new Date()
var futureDates = this.datoArray.filter(function (d) {
  return new Date(d) >= today;
})

Answer №3

In my opinion, the issue does not seem to be related to the dates.

It appears that the problem arises when trying to delete items from the array while simultaneously iterating through the same array.

One possible solution could be to iterate through the array in reverse order or keep track of the indexes that need to be removed before actually deleting them. It's important to remember that removing an item will shift the index of all remaining items - starting with the highest index might help avoid confusion.

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

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

Is there a way to continuously click on a button 99 times or until the code finishes running?

Need Assistance, Please Assist. I am encountering an issue where I have the same type of skip button with identical name and id properties for all products, but only the xpath changes. Can you provide guidance on how to efficiently click on 99 similar ski ...

Set maximum size for background image in div

I'm facing some challenges with setting the maximum height of a background image within a div. I want the max height to be equal to the actual height of the image, without stretching it. Ideally, if there is excess content in the div, it should stop a ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...

AngularJs stops the link from being clicked more than once

I am utilizing AngularJS for specific features in my system, not to build a single-page application. I am struggling to determine why Angular is preventing the page from refreshing after navigating there or how to disable/find a workaround. Here is an exa ...

Utilizing JSDoc annotations for type safety in VSCode with ESLint configuration for TypeScript declarations import

Is there a way to configure VSCode to perform syntax checking on .eslintrc.js and provide autocomplete functionality? I have managed to set up a structure for a JavaScript configuration file with a custom syntax for my application, but the same approach do ...

A guide on implementing isomorphic types in TypeScript

Consider the following scenario with two files, file.ts: let a: Message = "foo" let b: Message = "bar" let c: Message = "baz" Now let's introduce a second file, file2.ts type Message = string function fun(abc: Message): void { } When using functi ...

Alert: Route.get() is requesting a callback function, but is receiving an [object Undefined] while attempting multiple exports

I'm attempting to export the middleware function so that it can be called by other classes. I tried searching on Google, but couldn't find a solution that worked for my situation. Below is the code snippet: auth.js isLoggedIn = (req, res, nex ...

Place a hook following the storage of a variable in the device's memory

Within a component, I am facing the following situation: const [home, setHome]=useState(false) if(home){ return(<Redirect push={true} to="/" />); } setItem("isRegistered", resquest[0].user) setHome(true) The issue here is that ...

AngularJS factory or filter failing to update properly

I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes. Everything works fine if I define the language in the view beforehand, but when I t ...

Set up Vue.prototype prior to the component loading

In my Vuejs code, I am utilizing the plugins feature to define a global shared variable. Vue.use(shared) The shared variable is defined as follows:- export const shared = { config: getAppConfig() } shared.install = function() { Object.definePropert ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Using knex.js to pipe data to an express server

I'm encountering an issue with knex.js and express. Here is the code snippet in question: userRouter.get('/:userId', function (req, res) { DB('users').where({ id: req.params.userId }).first('name').pipe(res); }); ...

It is not possible to retrieve a cookie via a request

Currently, I am in the process of setting up an Express JS server that uses cookies. This is my first time incorporating cookies into a project :) Upon user login, I send cookies to them using the following code: res.cookie('pseudo', list[i].ps ...

What steps can I take to troubleshoot the 'Uncaught DOMException: failed to execute add on DOMTokenList' error?

I am looking to create media icons <div class="contact"> <span> <i class="fa fa-phone"></i> </span> <span> <i class="fa fa-facebook"></i> </spa ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Best practices for managing JWT tokens on the front-end with fetch requests and secure storage methods

Currently trying my hand at development, I am working on a task manager app where I've implemented JWT tokens for verification. While I managed to make it work on Postman, I'm stuck on how to store the token in a browser and send it to the server ...

What are some ways to manipulate JSON data following a successful AJAX request?

I've been grappling with this issue for quite some time now, trying various methods without any success. I won't bore you with the details of my failed attempts, but instead, I'll show you the code I'm currently working with. Here' ...

What is the process for incorporating multiple HTML pages into an Ionic hybrid mobile application?

Struggling to combine my sign in and sign up pages into a single index.html page. I'm currently working on a project involving Hybrid mobile app development. ...