Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Created March 19, 2020 15:22
Show Gist options
  • Save deepakshrma/ff30b8190edfe3a01b9ac59aa3d81cc9 to your computer and use it in GitHub Desktop.
Save deepakshrma/ff30b8190edfe3a01b9ac59aa3d81cc9 to your computer and use it in GitHub Desktop.
Sort any table
const sort_table = (
sortColNum,
id = "#table_data",
isLastRowTable = true,
formatter = td => td.textContent,
reIndex = 1
) => {
let elm = document.querySelector(id);
if (!elm) {
document.querySelector("table").tBodies[0].setAttribute("id", "table_data");
}
elm = document.querySelector(id);
const children = [...document.querySelector("#table_data").children];
document.querySelector("#table_data").innerHTML = "";
let lastRow;
if (isLastRowTable) lastRow = children.pop();
children
.sort(
(x, y) =>
formatter(y.children[sortColNum]) - formatter(x.children[sortColNum])
)
.forEach((x, index) => {
reIndex && (x.children[reIndex].textContent = index + 1);
elm.appendChild(x);
});
lastRow && elm.appendChild(lastRow);
};
sort_table(2, "#table_data", true, undefined, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment