Reorganizing an array of JSON data by date value with a limitation to just one

Currently, I am attempting to organize a JSON array based on the date key. However, it appears that my sorting function is either stopping after one sort or simply not functioning correctly.

Here is the JavaScript code for my sorting function:

  function sortByDate() {
        result = gloresult
        var newA = result.sort(function(a,b){
          return Number(new Date(a.Date)) - Number(new Date(b.Date));
        });

       console.log(newA)


      }

Input Json content

gloresult = [
    {
        "Heading": "A",
        "Topic A": "Ball Valve",
        "Date": "2/05/2019"
    },
    {
        "Heading": "B",
        "Topic A": "ABS",
        "Date": "1/05/2019"
    },
    //more data...
]

Output Json content

[
    {
        "Heading": "B",
        "Topic A": "ABS",
        "Date": "1/05/2019"

    },
    {
        "Heading": "A",
        "Topic A": "Ball Valve",
        "Date": "2/05/2019"

    },
    //more sorted data...
]

Upon examination, I noticed that only items A and B have switched positions while the rest of the results remain unchanged. I suspect this could be due to the way I am calling the function when a user selects a button on an HTML page.

Answer №1

The reason for the issue is that the dates are formatted as DD/MM/YYYY, while the Date constructor expects the format to be MM/DD/YYYY. As a result, when a new date in DD/MM/YYYY format is passed, it will return NaN if invalid. To resolve this, you can make a slight adjustment to your code inside the function:

const gloresult = [{"Heading":"A","Topic A":"Ball Valve","Date":"2/05/2019"},{"Heading":"B","Topic A":"ABS","Date":"1/05/2019"},{"Heading":"C","Topic A":"Acrylic","Date":"21/05/2019"},{"Heading":"D","Topic A":"Adaptor Fitting","Date":"21/05/2019"},{"Heading":"E","Topic A":"Air Gap","Date":"4/05/2019"},{"Heading":"F","Topic A":"Stuff","Date":"21/03/2019"},{"Heading":"G","Topic A":"Stuff","Date":"21/04/2019"},{"Heading":"H","Topic A":"Stuff","Date":"21/05/2021"}];

const sortByDate = () => {
  let result = gloresult;
  let newA = result.sort(({ Date: a }, { Date: b }) => {
    let [da, ma, ya] = a.split("/");
    let [db, mb, yb] = b.split("/");
    return Number(new Date([ma, da, ya].join("/"))) - Number(new Date([mb, db, yb].join("/")));
  });
  console.log(newA);
}

sortByDate();
.as-console-wrapper { max-height: 100% !important; top: auto; }

Answer №2

Although it presented a bit of challenge, I finally got it to work!

var
  gloresult = [ { "Heading": "A", "Topic A": "Ball Valve",      "Date": "2/05/2019"   }
              , { "Heading": "B", "Topic A": "ABS",             "Date": "1/05/2019"   }
              , { "Heading": "C", "Topic A": "Acrylic",         "Date": "21/05/2019"  }
              , { "Heading": "D", "Topic A": "Adaptor Fitting", "Date": "21/05/2019"  }
              , { "Heading": "E", "Topic A": "Air Gap",         "Date": "4/05/2019"   }
              , { "Heading": "F", "Topic A": "Stuff",           "Date": "21/03/2019"  }
              , { "Heading": "G", "Topic A": "Stuff",           "Date": "21/04/2019"  }
              , { "Heading": "H", "Topic A": "Stuff",           "Date": "21/05/2021"  }
              ];

gloresult.sort((a, b)=>{
  let
    aa = a.Date.split('/').reverse().map(d=>('0000'+d).slice(-4)).join('-'),
    bb = b.Date.split('/').reverse().map(d=>('0000'+d).slice(-4)).join('-');
  return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

// for (let x of gloresult ) console.log ( x.Date );
for (let x of gloresult ) console.log ( JSON.stringify( x ) );
.as-console-wrapper { max-height: 100% !important; top: auto; }

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

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

Try out the Jquery Chosen plugin, which allows you to select multiple instances of the same

I am currently using the chosen plugin to create multiple select input fields. You can view an example of this in action by following this link: By default, the plugin disables an option if it has already been selected. For instance, in the provided examp ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

Could not locate module: The package path ./react is not exported from the package in E:NextAppportfolio_website-mainportfolio_website-main ode_modules ext-auth

I am encountering an issue while trying to import SessionProvider from Next-Auth. The error message that is being displayed is: "Module not found: Package path ./react is not exported from package E:\NextApp\portfolio_website-main\port ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

Creating template variable based on $state in AngularJS

Here is what I currently have: <span>{{ $root.page_header || "default" }}</span> However, I want it to default to default unless the current $state is a specific value. For example, if my states are: home, settings, & profile, then I wan ...

Developing instance members and methods in JavaScript

After encountering a challenge with creating "private" instance variables in JavaScript, I stumbled upon this discussion. Prior to posing my question, I wanted to provide a thorough overview of the problem. My goal is to showcase a complete example of corr ...

What is the best way to extract data using Angular from the backend and then transfer it to the frontend using Node.js?

Recently, I decided to make a change in my node.js application. Previously, I was using the EJS template engine but now I want to switch to Angular. To do this, I have already installed Angular and it is working well. However, I am facing an issue while t ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

Guide to exporting everything within a div as a PDF using Angular 2

When attempting to convert a div with the id "div1" into a PDF using JSPdf in Angular 2, everything seems to be working fine until I try to export it to PDF. Here is my code snippet: <div class="container" id="div1"> <table> <tr> & ...

The Material-UI Button isn't able to trigger when the Popover is closed

Currently, I am working with Material-UI 4.11 and have implemented a Popover component along with a Button: Popover and Button <Popover id={id} open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: ...

Assigning batch variables based on the data within the variables

I need help with a coding task where I'm utilizing PowerShell to decode a JSON file and then using Batch to extract the results. I am trying to assign these results to variables, but I am unsure if it is possible to define the name of a variable based ...

iOS alert notification for navigator

How can I fix the issue with my alerts not working on my iOS project? I am using Ionic and AngularJS to develop my app. The problem I am facing is that when the alert pops up, the title shows as "index.html". This is how I call the alert: alert("aaa"); ...

Trouble with displaying an array of React elements in the render() function

While learning React by creating sample projects with Meteor, I've managed to grasp the basics but hit a wall. I'm utilizing a Twitter API to fetch the latest three tweets from the BOINGBOING Twitter page. The API is functional, and I can succes ...

What is the most effective method for displaying error messages in Extjs?

I am currently using the store.synch() method to post data, with validation being done on the server side. I am currently displaying error messages in a message box, but I want to explore alternative ways to show errors without having to use markInvalid( ...

Guide on displaying ajax data using PHP

I'm attempting to display the user-entered data by using AJAX to transfer it and then trying to print or echo it with PHP, but I'm having trouble getting it to work. enter code here Here is my code: <html> <head> <title> ...

What is the process for constructing an object to resemble another object?

After collecting input data, I have created an object based on those values. Here is an example of the generated object: var generate_fields = { name: "Mike", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d9dddf ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Adapt appearance according to the length of the text

Currently, I have an array that stores multiple strings based on displayed charts. My objective is to find the longest string within this array. So far, this task has been executed without any issues. The code snippet for this process is as follows: var ...

Prevent a div from being displaced by the transform property once it reaches the window's border

Is it possible to prevent the viewer I created using CSS transform from moving when its borders reach the window borders? Should I consider using a different method instead? If you'd like to see the code, you can check it out here. var x=0, y=0 ...