A guide on dividing date strings within a JavaScript array

When dealing with an array of Month/Day/Year datestrings like the one below...

const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"]

...my goal is to modify the array to exclude any datestrings (starting with 01 as the Day) that come after datestrings with 31 as the Day. Similarly, I want to remove instances of Day 30 followed by Day 01.

To achieve this, I loop through the strings in the array using a for statement. I then split each array item by "/" to separate MM, DD, and YYYY into individual variables.

for (let i = 0; i < array1.length; i++) {
  var [month, day, year] = array1[i].split('/');
  console.log(month, day, year)
}

Next, I plan to create a conditional that identifies if a date with 30 or 31 as the day is followed by a date with 01 as the day, enabling me to remove the subsequent 30th or 31st dates. To do this, I recombine month, day, and year into separate array items as shown below:

const newArray = []

for (let i = 0; i < array1.length; i++) {
  var [month, day, year] = array1[i].split('/');
  newArray.push(month + day + year)
  console.log(newArray)
}

This process generates the output:

 ['05312022', '06012022', '06022022']

However, I'm uncertain how to formulate a condition that checks for a date with 30 or 31 as the day being followed by a date with 01 as the day. What steps should I take to implement this check?

Answer №1

To filter out specific dates from an array of dates, you can iterate over the dates array. Extract the current day currDay and previous day prevDay, and check if the condition is met. If satisfied, you can slice the dates array and return the filtered result.

const filterDates = (dates) => {
  for (let i = 1; i < dates.length; i++) {
    const currDay = dates[i].slice(3, 5);
    const prevDay = dates[i - 1].slice(3, 5);
    if ((currDay === "01") & (prevDay === "31" || prevDay === "30")) {
      return dates.slice(0, i);
    }
  }
  return dates;
};

console.log(filterDates(["05/31/2022", "06/01/2022", "06/02/2022"]));

Answer №2

Utilizing the Array#reduce method, the goal is to:

  • Keep all elements unless:
  • The number of elements kept matches the current index, and the element at that index is dated with 01, following 30 or 31
  • If the current index exceeds the number of kept items (indicating some elements have been skipped), then the current element is skipped as well.

const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"],

      output = array1.reduce(
          (prev,cur,i) => 
          prev.length && ["30","31"].includes( prev.slice(-1)[0].slice(3,5) ) && 
          (prev.length === i && cur.slice(3,5) === "01" || i > prev.length) ?
              prev :
              [...prev, cur],
          []
      );
      
console.log( output );

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

Challenges with Vue and the <noscript> element

I recently deployed a vue app and everything seems to be functioning as expected. However, I encountered an issue when trying to view the page source in any browser - the actual content is not visible and instead, the body section starts with a message ins ...

Switch color in Material-UI based on props

Utilizing code inspired by the Material-UI documentation on customizing the switch, you can customize the switch color to be blue: import React from 'react' import Switch from '@material-ui/core/Switch' import {withStyles} from '@ ...

Controller data is being successfully returned despite breakpoints not being hit

While working with knockout Java-script, I encountered a perplexing issue. I have an API call to a controller which has several methods that are functioning correctly. However, when I set a break point on a specific method, it never gets hit. Strangely, da ...

Issue with JavaScript not generating a header element within a specified div

function searchingFunction() { var searchInput = document.getElementById("searchbar"); if (searchInput.value != null) { var resultElement = document.createElement("h2"); resultElement.innerHTML = "Search results for " + searchInput.value; d ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...

Exploring the concept of importing components from different pages in NextJS

I'm currently navigating the Next.JS framework and struggling to grasp the concept of importing data from a component page. Let's say I've created a page named example.js in my components folder, where I'm fetching data from an API to d ...

The jQuery Modal Dialog functions properly on the initial page load, but fails to work on subsequent pages unless manually refreshed

So, I've encountered an issue with my jQuery modal dialog. It's set up to remind non-registered users to sign up when they try to access user-only actions. Oddly enough, the dialog functions perfectly after a page refresh on THAT specific page. H ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

Having trouble with a JQuery ajax post to a PHP server - receiving the error message "SyntaxError: Unexpected token < in JSON at position 0"

I am attempting to transmit json data to a server and retrieve a json response. My code is displayed below: JS: function login() { console.log("clicked"); //gather form values into variables var email = $("#email").val(); var password = $("#password"). ...

The performance of three.js PointsMaterial is sluggish when utilizing large sprites or shapes, causing a decrease in overall

Currently, I am handling a point cloud with approximately 60,000 vertices. Interestingly, when I view the cloud at a smaller scale, performance remains acceptable. However, as soon as I zoom in and larger sprites/plans/points become visible on the screen, ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

Connecting Vue.js components together

I have two separate components - one for viewing data and another for editing the same data. The viewing component contains labels and paragraphs, while the editing component includes inputs and textareas. Both components are fed the same data object. Is ...

Can you provide instructions on how to utilize the fingerprintjs2 library?

I'm diving into the world of device identification with fingerprintjs2, but encountering a roadblock due to my inexperience with Libraries. The error message I keep running into is Uncaught ReferenceError: Fingerprint2 is not defined. Take a look at ...

Steps to set up a MessageCollector on a direct message channel

Hey everyone, does anyone have any tips on setting up the message.channel.createMessageCollector function for a direct message? I attempted to use message.author.dmChannel.createMessageCollector but it didn't work for me. Any advice? ...

`Formatting Dates with Google Script`

I am looking to modify the date format from "mmm-dd-yyyy" (Nov-11-2019) using my existing code. Here is the code snippet: var timeStamp = data[i][timeStampappr]; var formatted = (timeStamp.getMonth()+1) + '/' + timeStamp.getDate() + &ap ...

How can you transform a threejs perspective camera into an orthographic one?

After converting a perspective camera to an orthographic camera, I noticed that the model appears very tiny and hard to see. I have already calculated the zoom factor for the orthographic camera based on the distance and FOV, but I'm unsure if there a ...

Tips for inserting a DIV and SCRIPT from a single HTML template into a webpage

I'm working with an HTML template that contains a DIV with a button and a script with a function to call when the button is clicked: <div id="CLC_Form"> various text and checkbox inputs go here... <br> <input type="button" ...

What could be causing the consistent Mocha "timeout error" I keep encountering? Additionally, why does Node keep prompting me to resolve my promise?

I'm encountering a timeout error repeatedly, even though I have called done(). const mocha = require('mocha'); const assert = require('assert'); const Student = require('../models/student.js'); describe('CRUD Tes ...

Guide to emitting a value using the composition API

I'm currently working with a datepicker component that is part of a form in my Vue3 app using the composition API. My challenge is how to pass a value from the datepicker component back up to the form component. Unfortunately, I've encountered ...