views:

412

answers:

2

I have a table with a column of data that is mixed text and numbers. I'm sorting it using jQuery and the tablesorter plugin. The data that won't sort correctly is equipment tags, for example, "AHU-1", "AHU-2", "AHU-10". The problem is, given those example values, AHU-10 will be placed between AHU-1 and AHU-2. I've found forcing a 'digit' sort doesn't solve the problem.

Here's my question: 1) Does anyone know of an existing parser that I can use in this situation? If there isn't one then I'll need to write my own parser, in which case 2) How should I write the parser? Should I try and translate every letter to a number and do a numeric sort? That's my initial thought.

One more thing, I don't know for sure that a hyphen will be the delimiter. "AHU-1" could also be "AHU1", or "AHU 1", or "AHU:1", or something else.

A: 

Assuming all you need to do is sort any string of the pattern AAA-1 as AAA-01 you could do the following:

var myTextExtraction = function(node)  
{  
    // extract data from markup and return it  
    return node.childNodes[0].childNodes[0].innerHTML
               .replace(/([A-Z]{3}-)(\d)/,'$1-0$2'); 
} 
$(document).ready(function() 
    { 
        $("#myTable").tableSorter( {textExtraction: myTextExtraction} ); 
    } 
); 
Sam Hasler
I started with your code and then went through a bunch of iterations to try and get it to work, but none of what I did solved the problem. I'm going to look into the natural sort algorithms that ithcy suggested and go from there.
Jacob
A: 

You do need to write your own parser. What you are looking for is called "natural sort". There are plenty of javascript natural sort algorithms out there. I couldn't find one prewritten for the tablesorter plugin, but googling turns up quite a few.

ithcy
This is good information, thank you. Sometimes with Google you just need to know the right term (like "natural sort"). I'll let you know what I find.
Jacob