-1

I have a sorting function and 6 th tags inside my table element, and I want this function to somehow get the right attribute from my JSON file to sort. I tried the code below and it doesn't show any errors in console, but it doesn't sort table cells in any way.

$('#myTable th').on('click', function() {
    //figure out which panel to show
    var attrToSort = $(this).attr('rel');
    const ordered = people.sort((a, b) => a.attrToSort > b.attrToSort ? 1 : -1);
    console.table(ordered);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
        <thead>
          <tr>
            <th rel="id">id</th>
            <th rel="firstName">first name</th>
            <th rel="lastName">last name</th>
            <th rel="dateOfBirth">date of birth</th>
            <th rel="function">function</th>
            <th rel="experience">experience</th>
          </tr>
        </thead>
        <tbody class="suggestions">
        </tbody>
      </table>
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
Tomasz Czechowski
  • 255
  • 1
  • 2
  • 12

1 Answers1

1

attrToSort will be a string containing the name of the property, therefore you need to use bracket notation when accessing the object, not dot notation. Try this:

const ordered = people.sort((a, b) => a[attrToSort] > b[attrToSort] ? 1 : -1);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339