Skip to content

Instantly share code, notes, and snippets.

@LuisPaGarcia
Created August 17, 2023 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LuisPaGarcia/5f9cb46b981a4b75786071edf97ea76e to your computer and use it in GitHub Desktop.
Save LuisPaGarcia/5f9cb46b981a4b75786071edf97ea76e to your computer and use it in GitHub Desktop.
function sortTableByColumn(tableId, columnIdx) {
const table = document.getElementById(tableId);
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.getElementsByTagName('tr'));
rows.sort((rowA, rowB) => {
const cellA = rowA.getElementsByTagName('td')[columnIdx];
const cellB = rowB.getElementsByTagName('td')[columnIdx];
// Handle empty cells
const valueA = cellA ? parseFloat(cellA.textContent) : Number.NEGATIVE_INFINITY;
const valueB = cellB ? parseFloat(cellB.textContent) : Number.NEGATIVE_INFINITY;
return valueA - valueB;
});
for (let i = 0; i < rows.length; i++) {
tbody.appendChild(rows[i]);
}
}
// Usage example: Sort the table by the first column (index 0)
sortTableByColumn('myTable', 0);
In this updated version, we check for the existence of the cells in the specified column using the cellA and cellB variables. If a cell doesn't exist (empty <tr> tag), we assign a value of Number.NEGATIVE_INFINITY to ensure that empty cells are sorted to the bottom of the table.
This modification ensures that empty rows are handled correctly during the sorting process. Just like before, you can call the sortTableByColumn function with the appropriate arguments to sort the table by a specific column.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment