简体   繁体   中英

Sort table with javascript umlaute (ä,ö,ü) in html table

I have a html table, which is filled by a mysql query and initially sorted correcly. Now I found this possibility to sort the content by clicking the table headers. https://codepen.io/dcode-software/pen/zYGOrzK This works fine, but: When I sort by clicking a table header column, I have all the content beginning with "Umlaute" (ä, ö, ü, Ä, Ö, Ü) at the beginning of the table (DESC) or at the end (ASC). I tried to do my homework before asking, there seems to be a possibility whit LocalCompare, but I could not manage to insert this method in the code (I almost finished the php-course, soon starting JavaScript, anyway, would be nice, if the code would work with Umlaute).

Here the JavaScript:


function sortTableByColumn(table, column, asc = true)
{
    const dirModifier = asc ? 1 : -1;
    const tBody = table.tBodies[0];
    const rows = Array.from(tBody.querySelectorAll("tr"));

    //Sort each row
    const sortedRows = rows.sort((a, b) =>
        {
            const aColText = a.querySelector(`td:nth-child(${column + 1})`).textContent.trim();
            const bColText = b.querySelector(`td:nth-child(${column + 1})`).textContent.trim();

            return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);


        });

        //remove all existing TRs from the table
        while (tBody.firstChild) 
        {
            tBody.removeChild(tBody.firstChild);
        }

        // re-add the newly sortet rows
        tBody.append(...sortedRows);

        //remember how the column is currently sorted
        table.querySelectorAll("th").forEach(th =>th.classList.remove("th-sort-asc", "th-sort-desc"));
        table.querySelector(`th:nth-child(${column + 1})`).classList.toggle("th-sort-asc", asc);
        table.querySelector(`th:nth-child(${column + 1})`).classList.toggle("th-sort-desc", !asc);
}



document.querySelectorAll(".table-sortable th").forEach(headerCell => {
        headerCell.addEventListener("click", () => {
            const tableElement = headerCell.parentElement.parentElement.parentElement;
            const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell);
            const currentIsAscending = headerCell.classList.contains("th-sort-asc");

            sortTableByColumn(tableElement, headerIndex, !currentIsAscending);
        });
    });

You need to take String#localeCompare .

return aColText.localeCompare(bColText) * dirModifier;

To sort numbers correctly, you could check the values in advance and use

return dirModifier * (
    Number.isFinite(aColText) && Number.isFinite(bColText)
        ? (aColText - bColText)
        : aColText.localeCompare(bColText)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM