Skip to content

Instantly share code, notes, and snippets.

@Scemist
Last active September 11, 2023 18:29
Show Gist options
  • Save Scemist/222e8edcd4ec8408be5b4e481fbb8dcb to your computer and use it in GitHub Desktop.
Save Scemist/222e8edcd4ec8408be5b4e481fbb8dcb to your computer and use it in GitHub Desktop.
JavaScript Modern Table Sort
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