Discovering the earliest and latest dates within an array of date strings

My data consists of an array filled with objects like this

data = [
 {
  mas_name: (...),
  mas_plan_end: (...) // 'YYYY-MM-DD' eg: '2021-03-19'
  mas_plan_start: (...) // 'YYYY-MM-DD' eg: '2021-03-19'
  ...
 },
 {
  mas_name: (...),
  mas_plan_end: (...) 
  mas_plan_start: (...)
  ...
 }
]

Within the array, some objects may have mas_plan_start set to null. I aim to extract both the minimum and maximum values of mas_plan_start from this dataset. Attempting this task, I utilized moments in the following manner:

const max = moment.max(children.map((o) =>
          o.mas_plan_start ? o.mas_plan_start : moment(new Date()).format("YYYY-MM-DD")
        ));

const min = moment.min(children.map((o) =>
          o.mas_plan_start ? o.mas_plan_start : moment(new Date()).format("YYYY-MM-DD")
        ));

This approach led to the error depicted https://i.sstatic.net/3oiYh.png

Is there a way to resolve this issue or alternatively achieve the same goal without relying on moments?

To address this challenge, consider employing the following solution:

const max_date = moment.max(data.filter((o) =>
          o.mas_plan_end !== null
        ).map((date) =>
        moment(date.mas_plan_end, 'YYYY-MM-DD') // conversion to moment object for .max command functionality
        ));
      parent.mas_plan_end = max_date._i; // retrieving date String from moment instance

Answer №1

Although I have never utilized moment.js before, after reviewing your code snippet, it seems to be the way to go for date formatting.

const max = moment(data.map(obj => new Date(obj.mas_plan_end ?? '')).reduce((a, b) => b > a ? b : a)).format("YYYY-MM-DD");
const min = moment(data.map(obj => new Date(obj.mas_plan_start ?? '')).reduce((a, b) => b < a ? b : a)).format("YYYY-MM-DD");

The usage of the ?? operator in my code is known as the nullish coalescing operator, which returns the second value if the first one is null or undefined. Check out Nullish Coalescing MDN

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

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

How to turn off autocomplete for v-text-field in Vuetify

I'm using Vuetify's v-text-field component and I am trying to disable autocomplete. Even though I have included autocomplete="false", which is the correct syntax according to online sources, I am still seeing autocomplete suggestions. A ...

Styling Dropdown Options Based on Conditions in React

In my current project, I am attempting to modify the className of selected items within a mapped array using another array (this.props.notPressAble). The reason for this is because I want certain objects in the array to have a different CSS style. handleOp ...

Firefox Cookie Expiry Date Automatically Set to One Week in Default Settings

I recently encountered an issue while trying to create a cookie that would persist for a year. Interestingly, the code I used worked perfectly on Chrome, as I could verify by checking the "Storage" in the dev tools. However, when I tried the same code on F ...

using selenium to interact with elements within the window object

I'm a newcomer to selenium and javascript and looking to incorporate the VisualEvent javascript into pages opened in a selenium-controlled browser. My goal is to access its variables from selenium in java. I've successfully completed the first ph ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

What are the steps to configure MongoDB on Heroku using MongoHQ and Node.js?

I am currently using a local application, which is what I'm most familiar with. Heroku provided the following snippet of code: var mongo = require('mongodb'); var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || &apos ...

How to access a file stored within a proxy object using Vue.js

I am currently working on sending a file from a vue-page to the server. To achieve this, I have implemented the following: FileFrom component: <template> <div class="FileForm" v-bind:name="name"> <label clas ...

Next-auth is in need of a username for the credentials provider

I am currently trying to learn how to implement next-auth in Next.js 13. I have set up a credentials login system with username and password. When I make an API request, I expect to receive a status code of 200 if the credentials are correct. The logic f ...

Differences in file loading in Node.js: comparing the use of .load versus command-line

Currently, I am in the process of developing a basic server using vanilla JavaScript and Node.js. For this purpose, I have created a file named database.js, which includes abstractions for database interactions (specifically with redis). One of my objecti ...

Mongoose: execute population step after making the query

What is the proper way to populate the query result in Mongoose after executing a query similar to this: users .find({name:"doejohn"}) .skip(3) .limit(9) .exec((err,user) => { user // result ...

Leveraging deep linking to launch the email application in react native

I am currently exploring the deeplink URL for the mail app on iOS. A scenario I have set up involves displaying an alert that, when the user clicks 'ok', redirects them to the default mail app. const openEmailApp = () => { if (Platform.OS ...

pressing the enter key to submit form

Searching for videos is presenting a challenge for me when I try to submit the search form by pressing enter, but everything works fine when I click the button. After clicking, the text gets cleared and the /search page loads with the search index displa ...

Text-field input experiencing issues with placeholder display

As a beginner in Angular, I may make some mistakes. I created a textField input using a directive in Angular: .directive('textField', function () { return { restrict: 'E', scope: true, require: 'ngModel ...

What could be causing the data in the data table to remain undeleted unless the page is manually refreshed

I am facing an issue with the delete button functionality. When I press the button, it successfully deletes the row but requires a page refresh to make the deleted row disappear. How can I resolve this problem and ensure that the row is deleted without the ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

angular: handling duplicates in ng-repeat

Here is the JSON data: streams = [{ id: 0, codec_type: 'video', content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' }, { id: 1, codec_type: 'audio', content: '5.1(side) - cze - undefined' }, ...

Google Cloud Platform (GCP) reported a Stripe webhook error stating that no matching signatures were found for the expected signature

Current Stripe version: "8.107.0" I am encountering an issue with Stripe webhook verification whenever I deploy my webhook on Google Cloud Platform (GCP). Despite trying various methods to include the raw body in the signature, including the cod ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...