How to sort table values?

  • 0

    How to sort the table by age?
    <table id="grid">
        <thead>
          <tr>
            <th data-type="number">Возраст</th>
            <th data-type="string">Имя</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>5</td>
            <td>Вася</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Петя</td>
          </tr>
          <tr>
            <td>12</td>
            <td>Женя</td>
          </tr>
          <tr>
            <td>9</td>
            <td>Маша</td>
          </tr>
          <tr>
            <td>1</td>
            <td>Илья</td>
          </tr>
        </tbody>
      </table>
    JavaScript Anonymous, Sep 21, 2019

  • 1 Answers
  • 0
    const sort = {
    number: (a, b) => a - b,
    string: (a, b) => a.localeCompare(b),
    };

    function sortTable(table, colIndex) {
    if (typeof table === 'string') {
    table = document.querySelector(table);
    }

    const value = row => row.cells[colIndex].innerText;
    const compare = sort[table.tHead.rows[0].cells[colIndex].dataset.type];
    const tbody = table.tBodies[0];

    [...tbody.rows]
    .sort((a, b) => compare(value(a), value(b)))
    .forEach(n => tbody.append(n));
    }


    sortTable('#grid', 0);
    sortTable(document.querySelector('table'), 1);
    Juliet Bryan

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!