Home  >  Article  >  Web Front-end  >  How to Sort HTML Tables Alphabetically with JavaScript?

How to Sort HTML Tables Alphabetically with JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 22:23:02192browse

How to Sort HTML Tables Alphabetically with JavaScript?

Sorting HTML Tables with JavaScript

Many developers seek JavaScript solutions for sorting tables. A simple and effective solution is to sort each column alphabetically. This solution suits the need to disregard code, numbers, or currency and focus on the text.

Solution Overview

This solution involves adding a click event to each header cell. For the respective table, it locates all rows (except the first) and sorts them based on the clicked column's value. Once sorted, it re-inserts the rows into the table in the new order.

Implementation Details

  1. Event Handling: Add a click event to all th cells.
  2. Row Retrieval: Extract all rows except the first one (tr:nth-child(n 2)) from the clicked table.
  3. Sorting Logic: Create a sorting function comparer that takes two arguments: the column index idx and an asc flag. This function sorts rows based on the text content of the clicked column.
  4. Table Updates: After sorting the rows, append them back into the table in the new order.

Code Example in JavaScript and HTML

<code class="javascript">const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;

const comparer = (idx, asc) => (a, b) => ((v1, v2) =>
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
    )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

// Event Handling
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
    const table = th.closest('table');
    Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
        .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
        .forEach(tr => table.appendChild(tr) );
})));</code>
<code class="html"><table>
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>
    <tr><td>spain</td><td>2005-05-05</td><td></td></tr>
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>
    <tr><td>USA</td><td></td><td>-6</td></tr>
</table></code>

This solution efficiently sorts HTML tables alphabetically with a single click on the column header, without any external dependencies. Its simplicity and compatibility with major browsers make it a suitable option for many sorting needs.

The above is the detailed content of How to Sort HTML Tables Alphabetically with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn