Skip to content

Commit e144f39

Browse files
committed
fixes #1591
1 parent 9831b86 commit e144f39

File tree

1 file changed

+10
-6
lines changed
  • 2-ui/1-document/07-modifying-document/12-sort-table

1 file changed

+10
-6
lines changed

2-ui/1-document/07-modifying-document/12-sort-table/solution.md

+10-6
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,22 @@ The solution is short, yet may look a bit tricky, so here I provide it with exte
22

33

44
```js
5-
let sortedRows = Array.from(table.rows)
6-
.slice(1)
7-
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1);
5+
let sortedRows = Array.from(table.rows) // (1)
6+
.slice(1) // (2)
7+
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1); // (3)
88

9-
table.tBodies[0].append(...sortedRows);
9+
table.tBodies[0].append(...sortedRows); // (4)
1010
```
1111

12+
The step-by-step algorthm:
13+
1214
1. Get all `<tr>`, like `table.querySelectorAll('tr')`, then make an array from them, cause we need array methods.
1315
2. The first TR (`table.rows[0]`) is actually a table header, so we take the rest by `.slice(1)`.
1416
3. Then sort them comparing by the content of the first `<td>` (the name field).
1517
4. Now insert nodes in the right order by `.append(...sortedRows)`.
1618

17-
Tables always have an implicit `<tbody>` element, so we need to take it and insert into it: a simple `table.append(...)` would fail.
19+
Tables always have an implicit `<tbody>` element, so we must insert into it as `table.tBodes[0].append(...)`: a simple `table.append(...)` would fail.
20+
21+
Please note: we don't have to remove row elements, just "re-insert", they leave the old place automatically.
1822

19-
Please note: we don't have to remove them, just "re-insert", they leave the old place automatically.
23+
P.S. This solution assumes that the table doesn't have multple `<tbody>` (the common case). In case it does, we can modify the code accordingly: take rows only from the needed `<tbody>` in step `(1)` and insert them in that `<tbody>` step `(4)`.

0 commit comments

Comments
 (0)