Last active
September 11, 2023 18:29
-
-
Save Scemist/222e8edcd4ec8408be5b4e481fbb8dcb to your computer and use it in GitHub Desktop.
JavaScript Modern Table Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sortTableByColumn = (tableSelector, columnIndex) => { | |
const rows = document.querySelector(tableSelector) | |
.querySelectorAll(':scope > tbody > tr') | |
const getCellTextByPosition = row => { | |
const cell = row.querySelector(`:scope > *:nth-child(${columnIndex})`) | |
return cell == null ? '' : cell.innerText | |
} | |
const sortNaturally = (a, b) => getCellTextByPosition(a) | |
.localeCompare( | |
getCellTextByPosition(b), | |
undefined, | |
{ numeric: true, sensitivity: 'base' } | |
) | |
const sortedRows = Array.prototype.slice | |
.call(rows, 0) | |
.sort(sortNaturally) | |
const newTableBody = sortedRows | |
.reduce((rowList, row) => `${rowList}<tr>${row.innerHTML}</tr>`, '') | |
document.querySelector(`${tableSelector} > tbody`).innerHTML = newTableBody | |
} | |
sortTableByColumn('table', 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment