Custom Table Sorter In Vanilla JavaScript – Vi.Table.sort.js

Category: Javascript , Table | October 27, 2021
Author:coGit-ergo-sum
Views Total:90 views
Official Page:Go to website
Last Update:October 27, 2021
License:MIT

Preview:

Custom Table Sorter In Vanilla JavaScript – Vi.Table.sort.js

Description:

Vi.Table.sort.js is a standalone JavaScript library for soring table columns based on ‘string’, ‘number’, or a custom sort function.

How to use it:

1. Load the Vi.Table.sort.js library in the document.

<script src="./js/Vi.Table.sort.js"></script>

2. Apply built-in sorter functions to the table headers.

<table id="example">
  <thead>
    <tr>
      <th onclick="Vi.Table.sort.number(this)" title="Number will be sortes as number.">Numbers</th>
      <th onclick="Vi.Table.sort.string(this)" title="Strings will be ordered lessically.">Strings</th>
    </tr>
  </thead>
  <tbody> 
    ...
  </tbody>
</table>

3. Sort your table based on custom criteria.

function sortCustom(th) {
  try {
    var numbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    function getValue(tr, cellIndex) {
      var value = tr.children[cellIndex].innerText.toLowerCase().trim();
      return numbers.indexOf(value);
    }
    Vi.Table.sort(th, getValue);
  }
  catch (jse) {
    console.error(jse);
  }
}
<table id="example">
  <thead>
    <tr>
      <th onclick="sortCustom(this)" title="Strings will be ordered like the number they represent: custom sort.">Number</th>
      <th onclick="Vi.Table.sort.number(this)" title="Number will be sortes as number.">Numbers</th>
      <th onclick="Vi.Table.sort.string(this)" title="Strings will be ordered lessically.">Strings</th>
    </tr>
  </thead>
  <tbody> 
    ...
  </tbody>
</table>

You Might Be Interested In:


Leave a Reply