Hyphens make Tablesorter sort numeric fields uniquely

I have a table where data is displayed in the format of YYYY-####. Sometimes, there are values like 2012-456 and 2012-1234. By default, the sorting places 2012-1234 before 2012-456. If I change the sort to 'numeric', it disrupts the order of other years (for example, would sort as 2012-456, 2013-555, 2012-1234). My assumption is that I need to add leading zeros to the digits after the hyphen if they are less than 4 digits, but I haven't been successful in getting the sorter to work. I attempted using .addParser but am unfamiliar with it and have not found success. Are there any informative articles on this topic or does anyone have a solution?

Below is an illustration of sample data that is being sorted incorrectly and should be arranged by year (first 4 digits) followed by the number after the hyphen:

**Additionally, the date format could have, obviously, been better, but in this instance, I am unable to adjust how it is inputted.

Answer №1

Through thorough debugging efforts, I successfully managed to utilize .addParser() and minimized the code wherever possible. As a relatively new practitioner in javascript, I had overlooked the fact that the .length function also counts spaces and/or line breaks within my HTML.


$('.tablesorter').tablesorter({
    widgets: ['zebra'],
    headers: {
        0: {
            sorter: 'licenseYear'
        }
    }
})

$.tablesorter.addParser({
    id: 'licenseYear',
    is: function (s) {
        return false;
    },
    format: function (s) {
        //pad zeros for maximum digit length after hyphen
        var pad = "0000";
        //replace hyphen with necessary zeros to pad the number
        var n = s.replace(/-/, pad.substring(s.length - 5));
        return n;
    },
    type: 'numeric'
});

*UPDATE: Code optimization achieved with guidance from a discussion on left padding: convert '1' to '0001' in JavaScript

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

Merge the data from various sections of a JSON object into a unified array

Upon completing an ajax call to a specific URL, I receive data in the form of a JSON object structured like this: {"field1":["val1","val2","val3",...,"valn"], "field2":["vala","valb","valc",...,"valx"]} My goal is to merge the values of field1 and field ...

Aggregate the values of a key in an associative array and organize them by their respective key

I have a table set up like this: <table> <thead> <th>PRODUCT</th> <th>QUANTITY</th> <th>AREA</th> <th>PRICE</th> <th>TOTAL</th> <tr> &l ...

Passing a Ruby session variable to a JavaScript tag: a step-by-step guide

I'm currently collaborating with a vendor who utilizes a JavaScript tag for sale attribution, and I need to pass session variables to the tag. The tag appears to be firing properly, as I can see the variables in the logs, but they aren't reflecte ...

What is the best way to output a received HTML page from the server?

I'm currently working on printing an HTML page that was generated using Node.js on my server. After sending the page to the client side as a response to an AJAX request, I have stored it in a JavaScript variable. var resp_json = printRequest.getRespo ...

Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

Angular JS is facing difficulties in being able to call upon another directive

I'm encountering an issue where including another directive related to the current one results in the following error message Error: [$compile:ctreq] http://errors.angularjs.org/1.2.10/$compile/ctreq?p0=myApp.pagereel&p1=ngTransclude Script.js ...

What are the steps for setting up API REST calls proxy for a frontend hosted on Netlify?

While testing locally, I am able to successfully post a call and access it through Netlify. However, once I host the frontend app on Netlify, the POST Proxy is being set to the Netlify URL. The hosted URL: Upon clicking "Sign Up" and then clicking on "Si ...

Do not include iPad in the user agent redirect for iOS users

I have adapted a PHP script for detecting mobile devices into JavaScript, and it's working well. However, I want to specifically exclude tablet user agents. if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || ...

Incorporating a favicon into a Next.js React project

I'm currently working on integrating a favicon into a Next.js project that was generated using create-next-app. The favicon.png file is stored in the public folder, and I followed the instructions for serving static files outlined here. In my Layout ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...

Using jQuery to send a POST request with a data object

Trying to figure out something. Attempting to post an object using jQuery Ajax POST, like so: var dataPostYear = { viewType:GetViewType(), viewDate:'2009/09/08', languageId:GetLanguageId() }; $.ajax({ type: "POST", url: url ...

Delivering a Logo to a Remote Website Based on Specific Conditions

I am in the process of creating a code snippet for a specific user group that has earned the privilege to display our seal on their website. The concept initially appeared straightforward, but when I attempted to implement it on a different site for testin ...

Making an AJAX request in Javascript to retrieve multiple values using the HTTP method 'GET' from a URL

xmlhttp.open("POST","BAConsultRecordsAJAX.php?q="+str,true); Could this be achieved? xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str+"j="+str2,true); I need to have values stored in both q and j fields. ...

Guide to executing two child processes sequentially in Node JS

I am working on two processes within a function: one generates a JSON file from an audio while the other normalizes the generated JSON file. However, I'm facing an issue where only one of the processes runs at a time - when the first one runs, the se ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

Utilizing ID's within a jade template embedded within a P HTML element

Using the jade template, I successfully formed this paragraph. My next step is to add an ID or a class around the word stackoverflow. How can I achieve this in jade? I am aware that in regular HTML we would use something like <div class="className"> ...

Error: doc.data().updatedAt?.toMillis function is not defined in this context (NextJs)

I encountered an error message while trying to access Firestore documents using the useCollection hook. TypeError: doc.data(...)?.updatedAt?.toMillis is not a function Here is my implementation of the useCollection Hook: export const useCollection = (c, q ...

Tips on creating a button that, upon clicking, triggers the download of an Excel file using PHPSpreadsheet

I am trying to figure out how to create a button that, when clicked, will download an Excel file named b1b5.xls with some specified values added. Here is the code I have so far: <html> <head> </head> <body> <center> < ...