Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips?

Let's say we have an array object like:


data = [
    {id: "1", date: "18.08.2018"}
    {id: "2", date: "05.01.2014"}
    {id: "3", date: "01.01.2014"}
    {id: "4", date: "20.05.2016"}
]

The desired outcome is: when the button is clicked, data should be returned in chronological order like:


data = [
    {id: "3", date: "01.01.2014"}
    {id: "2", date: "05.01.2014"}
    {id: "4", date: "20.05.2016"}
    {id: "1", date: "18.08.2018"}
]

I attempted sorting based on dates and months but not accounting for the year with this code:


data.sort(function(a,b){return b.date - a.date});

Answer №1

To organize each item, you can convert them into dates and compare:

let items = [{
    id: "1",
    date: "18.08.2018"
  },
  {
    id: "2",
    date: "05.01.2014"
  },
  {
    id: "3",
    date: "01.01.2014"
  },
  {
    id: "4",
    date: "20.05.2016"
  },
]
//ascending
console.log(items.sort((a, b) => {
  var d1 = a.date.split('.'),
    d2 = b.date.split('.');
  return new Date(d1[2], d1[1] - 1, d1[0]) - new Date(d2[2], d2[1] - 1, d2[0]);
}));

//descending
console.log(items.sort((a, b) => {
  var d1 = a.date.split('.'),
    d2 = b.date.split('.');
  return new Date(d2[2], d2[1] - 1, d2[0]) - new Date(d1[2], d1[1] - 1, d1[0]);
}));

Answer №2

When comparing strings using basic comparison

It involves comparing each character based on their ASCII values


Sorting data by date in descending order

This doesn't work because

  1. b.date-a.date

    Subtracting day, month, and year in a string format

    For example, "30-10-2010" - "19-10-2019" results in a value greater than 0

    '3'-'1' is greater than 0 so it returns 1

    Similarly, "30-10-2010" - "31-10-2019" results in a value smaller than 0

    '3'-'3' =0 so it compares '0' to '1' which results in -1

  2. a.date b.date are treated as strings and using '-' might fail sometimes due to NaN issues

    Casting string to ASCII may lead to NaN errors

let data = [{
    id: "1",
    date: "18.08.2018"
  },
  {
    id: "2",
    date: "05.01.2014"
  },
  {
    id: "3",
    date: "01.01.2014"
  },
  {
    id: "4",
    date: "20.05.2016"
  },
]
var Rs=data.sort((a, b) => {
  var d1 = a.date.split('.');
  var d2 = b.date.split('.');
  return (d1[2]+d1[1]+d1[0]).localeCompare(d2[2]+d2[1]+d2[0]);
});
//Using basic string compare
//compare per char under ascii
var S1="Apple";
var S2="Apzle";
var S3="Apzle";
var S4="Apzle ";
console.log(S1.localeCompare(S2));
console.log(S2.localeCompare(S1));
console.log(S3.localeCompare(S3));
console.log(S3.localeCompare(S4));

console.log(Rs);

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

Incorporating a component specified in a .jsx file into a TypeScript file

We recently acquired a react theme for our web application, but ran into issues transpiling the components. After resolving that problem, we are now facing type-related challenges. It seems that TypeScript is struggling because the props do not have a def ...

Establish map boundaries using the longitude and latitude of multiple markers

Utilizing Vue, I have integrated the vue-mapbox component from this location: I've made sure to update the js and css to the latest versions and added them to the index.html: <!-- Mapbox GL CSS --> <link href="https://api.tiles.mapbox.com/m ...

How can I correct the error in accessing state data with a getter and displaying the outcome in a component?

I am relatively new to vuejs 3 and vuex 4. I'm currently attempting to create a simple getter, but when it didn't work as expected, I resorted to using console.log to check the output. The result that appeared in the console was: ComputedRefImpl ...

Tips for sending an icon as a prop in React components

I'm struggling to implement an icon as a prop while using props for "optionText" and "optionIcon". The optionText is working fine, but I'm facing issues with the OptionIcon. File where I'm creating props import Icon from ...

Unveiling the Evasive Final Element in a JavaScript Array

Having a Javascript array named full_range: const range1 = _.range(1, 10, 0.5); const range2 = _.range(10, 100, 5); const range3 = _.range(100, 1000, 50); const range4 = _.range(1000, 10000, 500); const range5 = _.range(10000, 105000, 5000); const full_ran ...

Response from the server to multiple asynchronous XMLHttpRequests

I'm in the process of creating a Web Application that involves making multiple simultaneous XHR calls using Ajax instead of native Javascript. $.ajax({ type: 'POST', url: 'Services/Service.asmx/MyFunction', contentTyp ...

I am encountering issues with running my tests using react-testing-library alongside TypeScript

Currently facing issues with react-testing-library in my TypeScript-based React project. Despite researching and following various tutorials, I am unable to resolve the problem. I have experimented with changing configurations in babel.config.js, tsconfig ...

Setting the y-axis range in d3.js and nvd3.js: A complete guide

I'm attempting to define the y-axis range of the chart to be between 1 and 100. After reviewing the API documentation, I came across a potential solution involving axis.tickValues which can be found here: https://github.com/mbostock/d3/wiki/SVG-Axes# ...

Script on the server side fails to execute following validation of form

Hey there, I'm struggling with my signup form. I want to submit the form using ajax after completing validation. I've used a jQuery plugin for validation, but whenever I click on any field, the ajax request is automatically sent to the server and ...

Presenting a 24-column data table fetched from MySQL and integrated into a webpage through JavaScript DataTables

Greetings everyone! I have a query regarding Javascript DataTables and how it displays data from a MySQL table. Here's the MySQL query in question: select LOT_LOCATION, `Zone Attribute`, a.LOTID, Design_ID, ifnul(Board_ID,'') as Board_ID1, ...

The step-by-step guide to testing an Angular promise using Jasmine

An issue arises when attempting to test the code below using Jasmine, as the console.log in `then` is never called. The question remains: is this problem related to Angular or Jasmine? describe("angular test", function() { var $q; ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

Transforming Javascript code using regular expressions into C#

Currently, I am facing a challenge while trying to translate some Javascript code into .NET. Despite my efforts, I have not been able to get it right. The task at hand involves converting paths like /test/:value1/:value2 in Express for NodeJS to a regular ...

Display a complex JSON string in an ng-grid

My web service is designed to generate a JSON string using the following code: JavaScriptSerializer j = new JavaScriptSerializer(); return "[" + string.Join(",", v.getProbingJobs().Select(a => j.Serialize(a)).ToArray()) + "]"; (The getProbingJobs func ...

Struggled to incorporate Typescript function overload's implementation

After reviewing the previous question: Typescript: exclude undefined/null properties from type In my TypeScript project, I attempted to create an overload for a function called request, which can optionally accept a payload. The function is defined by the ...

What is the method for obtaining the return type based on the type of a generic function?

Within my api function, I utilize a parser function that is generic and typically returns the same type as its input. However, in some cases, this may be different for simplification purposes. When using the api function, I am able to determine the type t ...

angular2 and ionic2 encounter issues when handling requests with observable and promises

I am attempting to trigger an action once a promise request has been resolved, but I'm having trouble figuring out how to achieve this. After doing some research, I learned that Ionic2 storage.get() returns a promise, and I would like to make an HTTP ...

Running the gulp uncss command with regex to ignore specific elements is not functioning as expected

I have been attempting to integrate uncss into my gulp workflow. In order to exclude certain classes, such as those added through javascript, I am specifying these classes with "ignore" (specifically, I am trying to remove the css from the jquery plugin m ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Issues arise when implementing Django templates in conjunction with jQuery

Here is an example of a Django template that I am working with: ... <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-primary" id="related"}>KIRK</button> </div> </div> . ...