Arranging data in a table by date with "."

My current use case involves working with a table that contains dates and empty strings. Despite expecting the sorting to behave a certain way, I've encountered an issue.

Normally, when sorting with strings, the empty string would typically be placed at the top or bottom of the sorted list. However, with dates, it seems to push them in between other values.

json = ['01-01-2018', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'];
this.json.sort((obj1: string, obj2: string) => {
  if (new Date(obj1) > new Date(obj2)) { return 1; }
  if (new Date(obj1) < new Date(obj2)) { return -1; }
  return 0;
});

As a result, the sorted list looks like this:

01-01-2018,,03-03-2018,04-03-2018,,03-03-2018,04-03-2018
.

For a demonstration, you can check out this Stackblitz example:

Stackblitz

I have attempted converting the values to numbers for sorting, but the issue with the empty strings persists. Does anyone have a solution to address this problem?

Answer №1

Ensure that the value can be converted to a date/time type before determining whether to return -1 or 1 (depending on your desired location).

json = ['01-01-2018', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'];
this.json.sort((obj1: string, obj2: string) => {
  if (obj1 === obj2) { return 0; } // return 0 if values are the same
  if (!obj1) { return 1; }
  if (!obj2) { return -1; }

  if (new Date(obj1) > new Date(obj2)) { return 1; }
  if (new Date(obj1) < new Date(obj2)) { return -1; }
  return 0;
});

Try this in Stackblitz

// Initial array
'01-01-2018', '', '', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'

// Sorted array
'01-01-2018', '03-03-2018', '03-03-2018', '04-03-2018', '04-03-2018', '', '', '', ''

Consider using momentjs over JavaScript's Date for more functionality and the ability to parse strings correctly using format strings.

Answer №2

Ensure the values are initialized:

 checkSorting(){
    this.data.sort((item1: string, item2: string) => {
      if (!item1 || !item2) {return -1}
      if (new Date(item1) > new Date(item2)) { return 1; }
      if (new Date(item1) < new Date(item2)) { return -1; }

      return 0;
    });
  }

output:

,,01-01-2018,03-03-2018,03-03-2018,04-03-2018,04-03-2018

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

Animated drop-down menu in Angular 4

I recently came across this design on web.whatsapp.com https://i.stack.imgur.com/ZnhtR.png Are there any Angular packages available to achieve a dropdown menu with the same appearance? If not, how can I create it using CSS? ...

Is there a method to enable the acceptance of both dots and commas as decimal markers in input fields?

Hey there! I have a question for you. Is there a way to allow users to input both commas and dots as decimal markers, but still display the value with dots and remove thousand separators? For example, when a user inputs "123456,78", they should see "123 ...

Unable to get the onchange event to trigger for a span element

Is there a way to trigger the onchange event on a span element that doesn't seem to be working? Here is the code I am using: Attempt 1 document.getElementById(seconds).addEventListener('change', (event: MutationEvent & { path: any }) =& ...

retrieving JSON data within HTML elements

How can I access the JSON values {{u.login}} from HTML instead of just through JavaScript? Currently, I am only able to access them using JS. Is there a way to directly access JSON values in HTML? At the moment, I am getting them as text. Could you please ...

Setting up configurations in an Angular app using environment variables from a Spinnaker manifest

In the spinnaker manifest, I have certain Environment-specific variables stored that I need to replace in my Angular app when it's deployed to different environments such as dev, qa, and prod. How can I modify my code to accomplish this? The reason be ...

Tips for effectively typing a collection of React wrappers in TypeScript

I encountered a situation in my team's application where we need the ability to dynamically compose component wrappers (HOCs) without prior knowledge of all the wrapper interfaces. This is mostly needed for swapping out context providers when renderin ...

When working on a node.js project with Angular, I'm considering incorporating a new HTML framework such as Foundation Zurb or Bootstrap. Is this a good idea, or should I stick

Is it necessary to use an additional HTML framework like Foundation Zurb or Bootstrap when using Angular in a node.js project? Can Angular alone handle the functionalities provided by Foundation Zurb / Bootstrap? Your insights would be greatly appreciated ...

Issue with Angular 8 - Material Table displaying incorrect data after deletion操作

I'm working on a material table that showcases different options through selects. My main object is the ngModel, which holds all the available options. These options are fetched from a database. Let's say I have a root item called menu, which m ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Using local variables in Angular2 templates

For the specific scenario discussed below, I have assigned the local variable #input to multiple radio buttons. My goal is to select the radio button within the <tr> when it is clicked. Surprisingly, the provided code functions as expected, yet the ...

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

Unlock specific elements within the "sub-category" of a combined collection

If my union type is structured like this: type StateUpdate = { key: 'surname', value: string } | { key : 'age', value: number }; This setup is convenient because it allows me to determine the type of the value based on the key. Howev ...

Guide to deploying Angular 17 in server-side rendering mode on Firebase

I've been delving into this issue for the past week, but still haven't found a definitive solution. I created an Angular 17 project in server-side rendering mode, installed Firebase via npm, built the project, used 'firebase init hosting&apo ...

Named functions in Typescript within functional components are the best practice for improving

How can I implement handleFoo using MyType['foo']? type MyType { foo: () => void } const Comp: React.FunctionComponent<{}> = () => { function handleFoo() {} return ... } I'm looking for a solution that doesn't inv ...

WebSocket establishing fresh connection every passing moment

My Angular 5 application uses a socket.io-client to connect to a websocket server hosted on the Google Cloud Platform. However, instead of opening just one connection, I noticed that multiple connections are being created in the browser, with a new conne ...

Steps for running a TypeScript project as a child process within a JavaScript project

I am facing an issue with integrating my Electron app, written mainly in JavaScript, with an Express server project built in TypeScript. When I attempt to create a child process of the TypeScript project within my electron.js file, I encounter TypeScript e ...

CRUD operation: The DELETE method is invoked prior to the user's request

Upon opening the localhost:4200 app, I noticed an old delete request already present. Even when I try to use the new delete request by clicking the button, it gives me a 404 (Not Found) error. However, manually entering the URL into the search bar does del ...

Error when casting Typescript await toPromise

I encountered the following issue: export class FloorManagerComponent implements OnInit { public meta = { list: [], building: Building, loading: true, }; constructor( private router: Router, private ac ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

Creating a table with a horizontal layout using Angular Material's mat-table

I am currently utilizing angular material 8.2.3 for my website. However, I have encountered a seemingly simple issue that has me stuck. I am looking to display a table horizontally instead of vertically. In my table, I only have two columns. Below is the ...