1

Building off of Nick Grealy's answer here: Sorting HTML table with JavaScript , I added additional sort criteria typical for most tables.

To help people looking for an all in one sort handling solution, what is the best way to sort prefixes and delimiters, and date as a string?

Additionally, should RegEx be used to recognize the delimiter used for thousands?

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)
  );

// do the work...
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));
  })
);
th {
  cursor: pointer
}

td {
  border: 1px solid;
  padding: 10px;
}
<table>
  <tr>
    <th>Country</th>
    <th>Date</th>
    <th>Date (text)</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>France</td>
    <td>2018-04-03</td>
    <td>Apr 03, 2018 10:30PM</td>
    <td>$2500</td>
  </tr>
  <tr>
    <td>spain</td>
    <td>2018-03-05</td>
    <td>Mar 05, 2018 12:19PM</td>
    <td>$11,000</td>
  </tr>
  <tr>
    <td>Lebanon</td>
    <td>2018-03-05</td>
    <td>Mar 05, 2018 04:30AM</td>
    <td>$980</td>
  </tr>
  <tr>
    <td>Argentina</td>
    <td>2018-09-13</td>
    <td>Sept 13, 2018 01:50AM</td>
    <td>$8100</td>
  </tr>
  <tr>
    <td>USA</td>
    <td>2017-012-17</td>
    <td>Dec 17, 2017 11:30AM</td>
    <td>$6000</td>
  </tr>
</table>
Kyle Underhill
  • 89
  • 15
  • 43

0 Answers0