Sorting complex strings in Typescript based on the dates contained within them

How can I sort a list of 2 strings with dates inside them so that the earlier one always comes first? The date is always after the second comma.

For example,

const example =
["AAA,5,2020-09-17T21:14:09.0545516Z",
"AAA,0,2020-09-03T20:38:08.3946643Z"]

sortStrings(example: string[]) {
  // how to sort to let earlier date come first
}

Answer №1

const data = ["ZZZ,10,2021-11-25T15:30:45.032612Z", "BBB,-5,2022-01-08T12:20:59.186422Z"]
data.sort((x, y) => new Date(x.split(",")[2]).getTime() - new Date(y.split(",")[2]).getTime())
console.dir(data);

Be cautious, this code snippet is just a simple example and not the most optimized way to sort an array based on dates.

Answer №2

arrangeWords(inputList: string[]){
    inputList.sort((word1, word2) => {
        var dataWord1 = word1.split(",");
        var dataWord2 = word2.split(",");
        var dateWord1 = new Date(dataWord1[dataWord1.length - 1]);
        var dateWord2 = new Date(dataWord2[dataWord2.length - 1]);
        return (dateWord1 > dateWord2 ? 1 : dateWord1 < dateWord2 ? -1 : 0);
    }
}

Answer №3

When considering the terms ascending and descending, they play a crucial role in answering certain questions. To illustrate this, here is a sample scenario:

const example = ["AAA,5,2020-09-17T21:14:09.0545516Z",
  "AAA,0,2020-09-03T20:38:08.3946643Z"
]

function desc(a, b) {
  a = a.split(",").pop();
  b = b.split(",").pop();
  let aDate = new Date(a);
  let bDate = new Date(b);
  if (aDate.getTime() > bDate.getTime()) {
    return -1;
  }
  if (aDate.getTime() < bDate.getTime()) {
    return 1;
  }
  return 0;
}

function asc(a, b) {
  a = a.split(",").pop();
  b = b.split(",").pop();
  let aDate = new Date(a);
  let bDate = new Date(b);
  if (aDate.getTime() < bDate.getTime()) {
    return -1;
  }
  if (aDate.getTime() > bDate.getTime()) {
    return 1;
  }
  return 0;
}
example.sort(desc);
console.log(example);
example.sort(asc);
console.log(example);

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

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

What is the process for modifying the popups associated with a polygon object?

As of now, every time I click on the map, a popup shows up with the name of the country based on a geoJSON file containing multi-polygon lnglat coordinates that outline the borders of each country. This method saves me from manually inputting each country& ...

What's the deal with the Zod getter function?

Is it possible to create a getter function within a Zod object? For instance, in ES5 you can achieve the following: const person = { firstName: "John", lastName: "Doe", get fullName() {return `${this.firstName} ${this.lastName}`} } person.fullNam ...

Issue with ESRI-Leaflet not displaying in an Angular Typescript environment due to a failure to recognize vector data

I am facing an issue where I cannot display the map or utilize the search functionality provided by esri-leafleft. Below is the code snippet from the typescript file: import { Component, OnInit } from '@angular/core'; import { Title, Meta } from ...

Endless Loop Issue with Google Maps API Integration in NextJS-React

Currently struggling to troubleshoot an infinite loop issue in my React function component map. I've spent a considerable amount of time analyzing the code and suspect that it might be related to the useEffects, but I'm unable to resolve it. Atta ...

Why is it necessary to create a new object in Node.js to establish a server?

After reviewing the information about socket.io, there is one aspect that I find confusing. I understand that to create a server, it can be done like this: var io = require ("socket.io")(); However, I am curious about why it necessitates creating a new ...

invoke a function through a form in Angular

I am encountering an issue with invoking a function from Angular. This particular function has a dual purpose - it uploads an image to S3 and saves the form data along with the URL of the image in the MongoDB database. Below is the HTML snippet where I cal ...

A guide on how to use Javascript to take a screenshot of an entire webpage

When a user triggers a script, it injects JavaScript code into the current page to make DOM changes. After interacting with the page, the user may want to save their modifications for later viewing or editing. However, if the original page source is edited ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

Tips on verifying the presence of a child in a Firebase list using AngularFire2

I am working on checking the existence of a Firebase list using AngularFire2 in Angular. Below is my parent list: https://i.sstatic.net/gSjEb.jpg I specifically need to verify if the child element Messages exists within this list. This is the code snip ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

When using Material UI, it is not possible to apply the text-overflow: ellipsis and overflow: hidden properties to multiple

I am new to material UI and here is the current state of my website: view reality of current website This is what I am expecting it to be: what I envision it becoming From the images above, you can see that I want the text inside the circle to be shorten ...

What could be causing the child of an ES6 imported object to return as undefined?

Here is the code snippet I am working with: import * as _routes from '../../routes' console.log('parent:', _routes) console.log('child:', _routes.breadcrumb) This code produces the following output: https://i.stack.imgur.co ...

Is it true that Firefox fails to display javascript errors on AJAX 'threads'?

Currently, I have a function called test_fn that is being called in two ways: (a) Through an onclick event of a button; or (b) from the success callback within a jQuery AJAX request, as shown here: $.ajax({ type: 'POST', ... succes ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

Does the resolve function within a Promise executor support async operations?

I'm trying to wrap my head around the following code: function myPromiseFunc() { return new Promise((resolve) => { resolve(Promise.resolve(123)); }); } We all know that the Promise.resolve method immediately resolves a Promise with a plain ...

Understand which form has been submitted

I have eight Forms in a page (Form0, Form1, Form2 and so forth). Each form, when submitted, sends data to ReassignPreg.php using JavaScript, which then searches for the data in the database and returns it as JSON. The corresponding divs on the page are the ...

The Angular Cli seems to be having trouble loading a State property and its reducer within the ngrx store all of

Following some minor changes to my application, I encountered an issue with my ngrx store not loading properly. While most of the store properties are displaying as expected and even fetching API results through their reducers, I am noticing that a crucial ...