Reputation: 105
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.
Upvotes: 1
Views: 3114
Reputation: 5589
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.
Upvotes: 1
Reputation: 12616
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} );
}
);
Upvotes: 1