Skip to content

Instantly share code, notes, and snippets.

@mrichman
Created January 30, 2020 11:41
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 mrichman/7d9949112caa4c6416c11a8742dda017 to your computer and use it in GitHub Desktop.
Save mrichman/7d9949112caa4c6416c11a8742dda017 to your computer and use it in GitHub Desktop.
Sort any HTML table by clicking a header
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) );
})));
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))}));
@mrichman
Copy link
Author

To use this from a browser bookmark, create a new bookmark and set the location to the contents of table.min.jsabove, prefixed by javascript:.

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment