LearnFrenzy
Sign in Take a free test

DOM Manipulation · DOM Coding Problems · Question 3

A sortable table in JavaScript Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The page contains this HTML:

<table id="t"><thead><tr><th data-key="name">Name</th><th data-key="score" data-type="number">Score</th></tr></thead><tbody></tbody></table>

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links