I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronological order). I have implemented a customSort function, but it is still producing the same incorrect sorting results specifically for the date column. Everything else in the table sorts properly except for this date column. Any suggestions or help would be greatly appreciated?

customSort(event: SortEvent) {
    event.data.sort((data1, data2) => {
      let value1 = data1[event.field];
      let value2 = data2[event.field];
      let result = null;
      if (value1 == null && value2 != null) {
        result = -1;
      } else if (value1 != null && value2 == null) {
        result = 1;
      } else if (value1 == null && value2 == null) {
        result = 0;
      } else if (typeof value1 === 'string' && typeof value2 === 'string') {
        const time1 = Date.parse('1970-01-01 ' + value1);
        const time2 = Date.parse('1970-01-01 ' + value2);
        console.log(value1);

        if (time1 < time2) {
          result = -1;
        } else if (time1 > time2) {
          result = 1;
        } else {
          result = 0;
        }
      } else {
        result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
      }
      return event.order * result;
    });
  }

I have also made some adjustments to the code but the sorting outcome remains the same.

customSort(event: SortEvent) {
    event.data.sort((data1, data2) => {
      let value1 = data1[event.field];
      let value2 = data2[event.field];
      let result = null;
      if (value1 == null && value2 != null) {
        result = -1;
      } else if (value1 != null && value2 == null) {
        result = 1;
      } else if (value1 == null && value2 == null) {
        result = 0;
      } else {
        const time1 = new Date(`1970-01-01 ${value1.padStart(5, '0')}`);
        const time2 = new Date(`1970-01-01 ${value2.padStart(5, '0')}`);
        const timestamp1 = time1.getTime();
        const timestamp2 = time2.getTime();
        if (timestamp1 < timestamp2) {
          result = -1;
        } else if (timestamp1 > timestamp2) {
          result = 1;
        } else {
          result = 0;
        }
      }
      return event.order * result;
    });
  }

Answer №1

What about incorporating a new attribute called "minutes" into the data?

data.forEach(item => {
   const values = item.date ? item.date.split(' ') : null;
   const hourMinutes = values ? values[0].split(":") : null;
   item.minutes = hourMinutes ? (+hourMinutes[0]) * 60 + (+hourMinutes[1]) : -999;
   if (values && values[1] == "pm")
       item.minutes += 12*60;
})

This way, the dataset will be sorted based on the minutes value.

<ng-container matColumnDef="date">
    <th mat-header-cell *matHeaderCellDef mat-sort-header="minutes">
       Date
    </th>
    <td mat-cell *matCellDef="let element"> {{element.date}} </td>
</ng-container>

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

Creating a JSON schema in JavaScript using an already established JSON framework

I have a json structure stored in a variable called "data" that looks like this: { "SearchWithMasterDataDIdAndScandefinitionDAO": [ { "dateDm_id": 20120602, "issueValue": "ELTDIWKZ", "scanName": "Company Stored as Person (Give ...

Tips for achieving compatibility between systemjs module loading and .net mvc architecture

Upon finding the ng-book 2, I saw it as a promising resource to delve into Angular 2. Although I am new to module loaders and have minimal experience with npm and node, I find the terminology and assumed knowledge to be quite perplexing. I decided to use ...

Is there a method to generate an endless carousel effect?

Hello, I am trying to create an infinite carousel effect for my images. Currently, I have a method that involves restarting the image carousel when it reaches the end by using the code snippet progress = (progress <= 0) ? 100 : 0;. However, I don't ...

Discovering the specific URL of a PHP file while transmitting an Ajax post request in a Wordpress environment

I'm currently working on a WordPress plugin and running into some issues with the ajax functionality. The main function of my plugin is to display a form, validate user input, and then save that data in a database. Here is the snippet of code for my ...

Arranging input elements horizontally

this issue is connected to this post: Flex align baseline content to input with label I am grappling with the layout of my components, specifically trying to get all inputs and buttons aligned in a row with labels above the inputs and hints below. The CSS ...

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

The type entity i20.CdkScrollableModule cannot be resolved to symbol in the nx workspace

After extensively researching online, I still haven't found a solution to this particular issue. I've attempted various troubleshooting steps, including deleting node_modules and package-lock.json, updating dependencies, and running nx migrate. ...

Tips for consolidating all functions into a single file for ReactJS inheritance:

I'm curious about something. In Angular JS, we have the ability to create a global service file that can be inherited by every component. This allows us to use the functions written in the global service file within each respective component. Is ther ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...

What steps should I follow to obtain code coverage data in my Aurelia application with the help of karma?

After creating my Aurelia app using the Aurelia CLI (au new), I wanted to set up code coverage, preferably with karma-coverage, but was open to other options as well. First, I ran npm install karma-coverage --save-dev and then copied the test.js task over ...

Insert HTML elements into nested CSS classes

My goal is to utilize jQuery for looping through classes and adding text to an HTML element. I am currently working with the following example HTML: <div class="question"> <div class="title"> <strong>Here's the question ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Looking for a way to view the files uploaded in a form using ajax?

Currently, I am encountering an issue while attempting to upload a file submitted in a form using PHP. To avoid page reloading, I have incorporated JS, jQuery, and AJAX between HTML and PHP. Unfortunately, I am facing difficulties with the $_FILES variable ...

I am having difficulty accessing the dataset on my flashcard while working with React/Next JS

I'm currently developing a Flashcard app that focuses on English and Japanese vocabulary, including a simple matching game. My goal is to link the two cards using a dataset value in order to determine if they match or not. When I click on a flashcar ...

Tips for isolating shared attributes within MUI Data Grid column configurations

Currently, I am developing a ReactJS Typescript Application using MUI as my component library. My goal is to create a comprehensive CRUD Datagrid similar to the MUI Datagrid component. In the example provided, many columns share common properties. To effic ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

A JavaScript right-click menu that updates a variable when clicked

Within my three-dimensional application created with three.js, I have implemented a functionality where right-clicking on floors (BoxGeometry) triggers a context menu to select from various textures. While this feature works as intended for a single floor, ...

How to Unsubscribe from an Angular 2 Subscription Automatically After a Timeout

I am looking for a way to disregard the response from my API in case it takes too long to fetch. Currently, I am using this.http.get(mysqlUrl).subscribe() to retrieve the response. However, I would like to terminate that subscription if it exceeds a dur ...

Having trouble with sending a list of items from a VueJS form

I have a VueJS application that calls a patch method to update a user's profile. For example, I am attempting to update the field cities. I created a serializer and views.py using Postman during development. I used Postman to call the patch method fo ...

Mixing success and error states can lead to confusion when using jQuery and Express together

I've been struggling with a simple question that's been on my mind for quite some time. Despite my searches, I haven't found a similar query, so I apologize if it seems too basic or repetitive. The scenario involves an API route (Express-ba ...