How to sort on hidden or data-attribute value in textSorter

Viewed 143

I have a "name" column in a table that contains a persons full name (ie. first+last name). The objective is to sort the column based on the person's last name first, then first name. My initial naive approach for the textsorter function was

function (a, b){
    const aSplit = a.split(' ');
    const bSplit = b.split(' ');
    const aReverse = aSplit[1] + aSplit[0];
    const bReverse = bSplit[1] + bSplit[0];
    return aReverse.localeCompare(bReverse);
}

Unfortunately, some of the names I have to sort have extraneous spaces in them, potentially in either the first name or last name field. So I have to support this in my sorting.

I am currently only using the combined first+last name string for display and sorting but I have access to the seperate name strings as well as a preformatted lastname, firstname version. I'd like to attach either of these to the <th> tags as a data attribute or something like that and sort using that instead of the actual value but I'm not sure how to go about accessing those attributes from within the textsorter function.

1 Answers

Maybe try this - when you build the table HTML, add the last name + first name into a data-text attribute of the cell. Tablesorter will automatically use that attribute over the actual text within the cell. See textAttribute option to allow changing that attribute name.

Related