This commit is contained in:
Ilya Kantor 2017-02-28 12:54:48 +03:00
parent 4272b7bb13
commit 508969c13f
168 changed files with 340 additions and 10 deletions

View file

@ -0,0 +1,19 @@
The solution is short, yet may look a bit tricky, so here I provide it with extensive comments:
```js
let sortedRows = Array.from(table.rows)
.slice(1)
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1);
table.tBodies[0].append(...sortedRows);
```
1. Get all `<tr>`, like `table.querySelectorAll('tr')`, then make an array from them, cause we need array methods.
2. The first TR (`table.rows[0]`) is actually a table header, so we take the rest by `.slice(1)`.
3. Then sort them comparing by the content of the first `<td>` (the name field).
4. Now insert nodes in the right order by `.append(...sortedRows)`.
Tables always have an implicit <tbody> element, so we need to take it and insert into it: a simple `table.append(...)` would fail.
Please note: we don't have to remove them, just "re-insert", they leave the old place automatically.

View file

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html>
<body>
<table id="table">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
</tr>
<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>
</table>
<script>
let sortedRows = Array.from(table.rows)
.slice(1)
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1);
table.tBodies[0].append(...sortedRows);
</script>
</body>
</html>

View file

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<body>
<table id="table">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
</tr>
<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>
</table>
<script>
// ... your code ...
</script>
</body>
</html>

View file

@ -0,0 +1,39 @@
importance: 5
---
# Sort the table
There's a table:
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
</tr>
<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>
</table>
There may be more rows in it.
Write the code to sort it by the `"name"` column.