Render the students into the table body, and make clicking a header sort by that column – ascending on the first click, descending on the next – using the data-key and data-type attributes.
Solution
main.js
const students = [{ name: "Ravi", score: 78 }, { name: "Asha", score: 92 }, { name: "Meera", score: 85 }];
const table = document.getElementById("t");
const tbody = table.tBodies[0];
let sortKey = null, direction = 1;
function render(rows) {
tbody.replaceChildren(...rows.map((s) => {
const tr = document.createElement("tr");
tr.append(...[s.name, s.score].map((v) => Object.assign(document.createElement("td"), { textContent: v })));
return tr;
}));
}
table.tHead.addEventListener("click", (e) => {
const th = e.target.closest("th");
if (!th) return;
const { key, type } = th.dataset;
direction = key === sortKey ? -direction : 1;
sortKey = key;
const compare = type === "number" ? (a, b) => a[key] - b[key] : (a, b) => a[key].localeCompare(b[key]);
render([...students].sort((a, b) => direction * compare(a, b)));
});
const show = (label) => console.log(label.padEnd(12), [...tbody.rows].map((r) => r.cells[0].textContent).join(", "));
const [nameTh, scoreTh] = table.tHead.rows[0].cells;
render(students); show("original:");
nameTh.click(); show("name ↑:");
scoreTh.click(); show("score ↑:");
scoreTh.click(); show("score ↓:");
Output Verified by running it on Node.js
original: Ravi, Asha, Meera
name ↑: Asha, Meera, Ravi
score ↑: Ravi, Meera, Asha
score ↓: Asha, Meera, Ravi
The header row has one delegated listener; data attributes describe each column, so adding a column needs no new code. Sorting a copy keeps the original order available.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!