Generate a pair of dates and organize them in chronological order

Working on an application where the database response lacks a direct timestamp, causing data to render differently each day and requiring me to use .reverse() to fix my charts. I aim to implement a permanent solution using sort(), but struggling due to the absence of direct timestamps in the response.

The API provides examples responses as follows:

"records": [
    { 
      "dateRep": "01/05/2020",
      "day": "1",
      "month": "5",
      "year": "2020",
      "cases": "222",
      "deaths": "4",
      "countriesAndTerritories": "Afghanistan",
      "geoId": "AF",
      "countryterritoryCode": "AFG",
      "popData2018": "37172386",
      "continentExp": "Asia"
    }, 
    { 
      "dateRep": "30/04/2020",
      "day": "30",
      "month": "4",
      "year": "2020",
      "cases": "122",
      "deaths": "0",
      "countriesAndTerritories": "Afghanistan",
      "geoId": "AF",
      "countryterritoryCode": "AFG",
      "popData2018": "37172386",
      "continentExp": "Asia"
    }, 
    { 
      "dateRep": "29/04/2020",
      "day": "29",
      "month": "4",
      "year": "2020",
      "cases": "124",
      "deaths": "3",
      "countriesAndTerritories": "Afghanistan",
      "geoId": "AF",
      "countryterritoryCode": "AFG",
      "popData2018": "37172386",
      "continentExp": "Asia"
    }, 

The current code is not functioning as expected:

for (var i = 0; i < countriesList.length; i++) {
    dataWorldWideEuropa.sort(
        (a, b) => new Date(a.year,a.month,a.day) > new Date(b.year,b.month,b.day)
    ).map(datum => {
    // do work here
    });
}

Is there a way to convert the .day, .month, and .year fields from the response into a Date format for sorting purposes without relying on .reverse() when the API changes?

Answer №1

If you want to arrange your data in a specific order, you can achieve this by using the .sort() method on your array and calculating the difference between the elements:

return new Date(a.year, a.month, a.day) - new Date(b.year, b.month, b.day);

The sorting function compares two items at a time and returns a value less than 1, greater than 1, or zero depending on their relationship.

const sorted = getRecords().sort((a,b) => {
  return new Date(a.year, a.month, a.day) - new Date(b.year, b.month, b.day);
});

console.log(sorted)

function getRecords(){

  return [
    { 
      "dateRep": "01/05/2020",
      "day": "1",
      "month": "5",
      "year": "2020",
      "cases": "222",
      "deaths": "4",
      "countriesAndTerritories": "Afghanistan",
      "geoId": "AF",
      "countryterritoryCode": "AFG",
      "popData2018": "37172386",
      "continentExp": "Asia"
    }, 
    { 
      "dateRep": "30/04/2020",
      "day": "30",
      "month": "4",
      "year": "2020",
      "cases": "122",
      "deaths": "0",
      "countriesAndTerritories": "Afghanistan",
      "geoId": "AF",
      "countryterritoryCode": "AFG",
      "popData2018": "37172386",
      "continentExp": "Asia"
    }, 
    { 
      "dateRep": "29/04/2020",
      "day": "29",
      "month": "4",
      "year": "2020",
      "cases": "124",
      "deaths": "3",
      "countriesAndTerritories": "Afghanistan",
      "geoId": "AF",
      "countryterritoryCode": "AFG",
      "popData2018": "37172386",
      "continentExp": "Asia"
    }
  ]
}  

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

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

Deleting uploaded images in Cloudinary for Next.js is not allowed

After successfully implementing image uploads in cloudinary for Next.js, I encountered an issue with image deletion. Despite creating the necessary routes and components, the deletion functionality is not working as expected. I am unsure of what could be ...

Methods for accessing data from a Nested JSON in Swift

Recently, I've been working on a project in Swift that involves handling a nested JSON file. The JSON data is structured with categories and exercises within each category, as shown below: { "categories": [ { ...

Ending the Firefox browser using JavaScript

I have been trying to use the basic window close javascript command window.close(); but it seems to only work in IE and not in any other browser. Can anyone provide assistance on how to successfully close a browser tab in Firefox, Opera, or Chrome? Thanks ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

The Jquery ajax call encountered an error due to a SyntaxError when trying to parse the JSON data, specifically finding an unexpected character at

I've developed a web application that utilizes just four scripts for dynamic functionality. Overview: Init.php = Database, index.php = webpage, api.php = fetches data from server/posts data to server, drive.js = retrieves information from api.php a ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

Searching for empty array fields in a jsonb column using a PostgreSQL query

device_id | device ----------------------------- 9809 | { "name" : "printer", "tags" : [] } 9810 | { "name" : "phone", "tags" : [{"count": 2, "price" : 77}, {"count": 3, "price" : 37} ] } When running a postgres SQL query on a jsonb column n ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

Stop the link action following a delay after the mouse is clicked

I'm currently troubleshooting a function that should prevent users from being redirected when clicking and holding onto a link for more than one second. However, the function I implemented is not functioning as expected. I have spent some time reviewi ...

Trouble with CSS and JS tabs not activating when clicked?

I am experiencing issues with a navigation (organized in tabs) that is not functioning on this page, but it works correctly on this page using the same method for inclusion. When clicking "Norway" on the top left, the navigation opens but switching to the ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Is it always the case that modifying the props of a child component will trigger a re-render of the parent component, even

I am currently exploring ways to prevent a modal element from re-rendering when it is supposed to be hidden. The tutorial I am following suggests converting the component to a class-based one and using shouldComponentUpdate(). However, I wanted to test if ...

Showing JSON information on a web browser

Here is a snippet of JSON data that I am working with: {"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.36899999999999977262632455676794 ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

"Encountering a strange behavior in Vue.js: the created() hook

I made a custom feature to refresh my data from the database by clicking a button: <template> <base-projects :projects="projects" /> </template> <script> import { mapGetters } from 'vuex'; import Projects from './ ...

Save modified content in CKEditor to an HTML document

Currently, I am utilizing the Ajax success function to dynamically load the content from an HTML file into CKeditor. function retrieveFileContent(fileUrl) { $.ajax({ url: fileUrl, success: function (data){ ...

Adding semi-colon in JavaScript with special comments by YUI Compressor

Our team recently implemented YUI Compressor (2.4.8) on our project and it's been performing well. However, we encountered an unexpected issue while minifying JavaScript files that contain special comments. It appears that YUI Compressor is automatic ...

Protractor encounters a TypeError when attempting to navigate with Firefox version 59 due to a cyclic object value

Our team has implemented several Protractor tests for our Angular JS application. Recently, we considered upgrading the Firefox browser to version 59 while using Selenium 3.11.0. However, after the upgrade, whenever we try to use element(by. in our tests ...

Getting dynamic variables in the `getStaticProps` function of NextJS can greatly enhance

I am working on utilizing getStaticProps in order to fetch data based on a variable. Here is a sample code snippet: export async function getStaticProps() { const res = await fetch(localWordpressUrl, { method: 'POST', headers: { 'C ...