Question: I am working on an HTML project containing a sortable data table. All my columns are being processed as a string though. I need to

I am working on an HTML project containing a sortable data table. All my columns are being processed as a string though. I need to make sure if the table column is a date or integer it will sort correctly. Here is my javascript so far. Any suggestions?

/**

*

* @param {HTMLTableElement} table

* @param {number} column

* @param {boolean} asc

*/

function SortTableByColumn (table, column, asc = true){

const dirMod = asc ? 1 : -1;

const tbody = table.querySelector('tbody');

const rows = Array.from(tbody.querySelectorAll("tr"));

if (!tbody) {

console.error('Could not find table body element.');

return;

}

// 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();

const aColValue = isNaN(Date.parse(aColText)) ? aColText : new Date(aColText).getTime();

const bColValue = isNaN(Date.parse(bColText)) ? bColText : new Date(bColText).getTime();

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

});

//remove all existing TRs from the table

while (tbody.firstChild) {

tbody.removeChild(tbody.firstChild);

}

//readd newly sorted 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 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);

});

});

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!