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

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point. Alt ...

Axios failing to include Content-Type in header

I have set up an Odoo instance in the backend and developed a custom module that includes a web controller. Here is the code for the web controller: Web Controller # -*- coding: utf-8 -*- from odoo import http import odoo from odoo.http import Response, ...

What are the steps for combining two constants with the JSON format of "const = [ { } ]"?

Here is the initial code that I would like to merge with another section. const sections = [ { title: section1_title, rows: [{ title: section1_option01, rowId: "sec1_option01", ...

Automatically integrating Nivo Lightbox into your website

I incorporated Nivo Lightbox into my website, seamlessly integrating all images with the plugin using the following code: <div class="portfolio-item"> <div class="portfolio-thumb "> <a class="lightbox" data-lightbox-type="ajax" title="Strat ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error. ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

Change the name of the interface from the imported type

When working with Google Apps Script, I have implemented the Advanced Calendar Service, originally labeled as "Calendar". However, I have renamed it to "CalendarService". How can I incorporate this name change when utilizing the type definitions for Apps S ...

What is the best way to fill a list-group using JavaScript?

Fetching ticket data from a controller is done using the code snippet below: $.ajax({ type: "GET", url: "/Tickets/List/", data: param = "", contentType: "application/ ...

Tips for effectively managing loading state within redux toolkit crud operations

Seeking guidance on efficiently managing the loading state in redux-toolkit. Within my slice, I have functionalities to create a post, delete a post, and fetch all posts. It appears that each operation requires handling a loading state. For instance, disp ...

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Updating an iframe's content URL

I am currently working on building a website using Google Web Design and everything is going well so far. I have added an iFrame to the site and now I am trying to figure out how to change its source when a button is pressed. Most of the information I fo ...

connect the input to a factor using v-model

I currently have a value that I need the user to adjust. Here's my current setup: <input type="number" v-model="value" step="any"/> However, the internal value is in radians while I want the user to see and input a degree value. So, I want th ...

Retrieve a div element using two specific data attributes, while excluding certain other data attributes

Here are some examples of divs: <div id="1" data-effect-in="swing" data-effect-out="bounce"></div> <div id="2" data-effect-in="swing"></div> <div id="3" data-effect-out="swing"></div> <div id="4" data-effect-out data ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

Utilize a generic approach for every element within a union: Transforming from Some<1 | 2 | 3> to individual Some<1>, Some<2>, or Some<3> instances

As I was unable to create a concise example for my issue, this is a general rendition of it. I am facing a scenario where the "sequence of application" is vital in nested generics. type Some<A> = {type: A} type Union1 = Some<1 | 2 | 3> type Uni ...