Created
January 30, 2020 11:41
-
-
Save mrichman/7d9949112caa4c6416c11a8742dda017 to your computer and use it in GitHub Desktop.
Sort any HTML table by clicking a header
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 getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent; | |
const comparer = (idx, asc) => (a, b) => ((v1, v2) => | |
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2) | |
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx)); | |
// do the work... | |
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => { | |
const table = th.closest('table'); | |
Array.from(table.querySelectorAll('tr:nth-child(n+2)')) | |
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc)) | |
.forEach(tr => table.appendChild(tr) ); | |
}))); |
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 getCellValue=(e,r)=>e.children[r].innerText||e.children[r].textContent,comparer=(e,r)=>(t,l)=>((e,r)=>""===e||""===r||isNaN(e)||isNaN(r)?e.toString().localeCompare(r):e-r)(getCellValue(r?t:l,e),getCellValue(r?l:t,e));document.querySelectorAll("th").forEach(e=>e.addEventListener("click",()=>{const r=e.closest("table");Array.from(r.querySelectorAll("tr:nth-child(n+2)")).sort(comparer(Array.from(e.parentNode.children).indexOf(e),this.asc=!this.asc)).forEach(e=>r.appendChild(e))})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use this from a browser bookmark, create a new bookmark and set the location to the contents of
table.min.js
above, prefixed byjavascript:
.It would look like this:
javascript:const getCellValue=(e,r)=>e.children[r].innerText||e.children[r].textContent...
To use sort an HTML table, click the bookmark you just created and click a table header. Magic! (Tested only in Firefox)