javve / list.js

The perfect library for adding search, sort, filters and flexibility to tables, lists and various HTML elements. Built to be invisible and work on existing HTML.
https://listjs.com
MIT License
11.2k stars 898 forks source link

Best way to force "alphabetical" sort on numbers? #776

Open jyoungblood opened 2 months ago

jyoungblood commented 2 months ago

Hello, I have what I'd guess is an uncommon use case where I need to use a different sorting behavior than the default, treating numbers as strings.

I'm working on a commercial real estate dashboard where I have tables that are lists of addresses/codes that are technically names, but they start with numbers (ex: 15712-NP | Ste 9, 15812-NP | Ste 1, 3825-NW166 | Ste C3-H, 3801-NW166 | Ste 5, etc)

Whenever I sort these fields, their value as a whole number is parsed. However, I'd like their order to be determined character-by-character.

For example, using the numbers above, an ASCENDING sort shows in this order:

(numbers that start with "1" are at the end because they have more digits and are technically greater in value than the "smaller" numbers that start with "3")

But I'd like for it to show in this order:

Just a standard alphabetical sort that doesn't consider the actual value of a set of numbers.

I came up with a solution that technically works, but it feels a little too hacky. I'm sorting with content from a data attribute and inserting spaces after every character (with PHP on page load), here's an example:

const list = new List('list-vacancies', {
  sortClass: 'table-sort',
  listClass: 'table-tbody',
  valueNames: [
    { attr: 'data-suite', name: 'sort-suite' },
    'sort-site',
    'sort-vacancy',
  ]
});
<table id="list-vacancies">
  <thead>
    <tr>
      <th class="table-sort" data-sort="sort-suite">SUITE</th>
      <th class="table-sort" data-sort="sort-site">SITE</th>
      <th class="table-sort" data-sort="sort-vacancy">VACANCY %</th>
    </tr>
  </thead>
  <tbody class="table-tbody">

    <tr>
      <td class="sort-suite" data-suite="1 5 7 1 2 - N P | S t e 9">15712-NP | Ste 9</td>
      <td class="sort-site">{{development}}</td>
      <td class="sort-vacancy">{{vacancy_percentage}}%</td>
    </tr>

    <tr>
      <td class="sort-suite" data-suite="3 8 2 5 - N W 1 6 6 | S t e C 3 - H">3825-NW166 | Ste C3-H</td>
      <td class="sort-site">{{development}}</td>
      <td class="sort-vacancy">{{vacancy_percentage}}%</td>
    </tr>

    <tr>
      <td class="sort-suite" data-suite="3 8 0 1 - N W 1 6 6 | S t e 5">3801-NW166 | Ste 5</td>
      <td class="sort-site">{{development}}</td>
      <td class="sort-vacancy">{{vacancy_percentage}}%</td>
    </tr>

  </tbody>
</table>

So my question is: is there an easier way to use a different sorting method on specific columns?