돌아가기
이 글은 다음 언어로만 작성되어 있습니다. English, 日本語, Русский, Türkçe, 简体中文. 한국어 번역에 참여해주세요.

Sort the table

중요도: 5

There’s a table:

<table>
<thead>
  <tr>
    <th>Name</th><th>Surname</th><th>Age</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>John</td><td>Smith</td><td>10</td>
  </tr>
  <tr>
    <td>Pete</td><td>Brown</td><td>15</td>
  </tr>
  <tr>
    <td>Ann</td><td>Lee</td><td>5</td>
  </tr>
  <tr>
    <td>...</td><td>...</td><td>...</td>
  </tr>
</tbody>
</table>

There may be more rows in it.

Write the code to sort it by the "name" column.

샌드박스를 열어 정답을 작성해보세요.

The solution is short, yet may look a bit tricky, so here I provide it with extensive comments:

let sortedRows = Array.from(table.tBodies[0].rows) // 1
  .sort((rowA, rowB) => rowA.cells[0].innerHTML.localeCompare(rowB.cells[0].innerHTML));

table.tBodies[0].append(...sortedRows); // (3)

The step-by-step algorthm:

  1. Get all <tr>, from <tbody>.
  2. Then sort them comparing by the content of the first <td> (the name field).
  3. Now insert nodes in the right order by .append(...sortedRows).

We don’t have to remove row elements, just “re-insert”, they leave the old place automatically.

P.S. In our case, there’s an explicit <tbody> in the table, but even if HTML table doesn’t have <tbody>, the DOM structure always has it.

샌드박스를 열어 정답을 확인해보세요.