jQuery:複数の列値でテーブルを並べ替える

JamesG

私はしばらくこれに苦労していて、何かをテストするたびに、異なる結果が得られることになります。

JSFIDDLE

テスト用の基本的なテーブルがあり、名前、年齢、参加日という3つの異なる見出しを持つ3つのエントリがあります。

表は次のとおりです。

<table class="table">
<thead>
  <tr>
    <th scope="col">#</th>
    <th scope="col" id="firstName">name</th>
    <th scope="col" id="age">age</th>
    <th scope="col" id="date">date joined</th>
  </tr>
</thead>
<tbody>
  <tr>
    <th scope="row">1</th>
    <td class="firstName">Mark</td>
    <td>12</td>
    <td>12/02/2006</td>
  </tr>
  <tr>
    <th scope="row">2</th>
    <td class="firstName">Jacob</td>
    <td>30</td>
    <td>03/04/2018</td>
  </tr>
  <tr>
    <th scope="row">3</th>
    <td class="firstName">Larry</td>
    <td>22</td>
    <td>07/01/2009</td>
  </tr>
</tbody>

これが私のJSです:

function sortTable(column) {
        var $tbody = $('.table tbody');
        $tbody.find('td.' + column).sort(function(a,b){ 
            var tda = $(a).find('td:eq(1)').text();
            var tdb = $(b).find('td:eq(1)').text();
                    // if a < b return 1
            return tda < tdb ? 1 
                   // else if a > b return -1
                   : tda > tdb ? -1 
                   // else they are equal - return 0    
                   : 0;           
        }).appendTo($tbody);
}

$('#firstName').click(function() {
    sortTable("firstName");
});
$('#age').click(function() {
    sortTable("age");
});
$('#date').click(function() {
    sortTable("date");
});

私が達成しようとしていること

各ヘッダーをクリックして、それぞれのコンテンツでテーブルを並べ替えることができるようにしたいと思います。たとえば、名前をクリックすると、名前で並べ替えられます。年齢をクリックすると年齢で並べ替えられ、参加した日付をクリックすると日付で並べ替えられます。

私も本当に学びたいので、何が起こっているのかを説明できる良いコメントがある答えに対して100ボーナスポイントを与えます。

ありがとうございました。

function sortTable(column) {
  var $tbody = $('.table tbody');
  $tbody.find('td.' + column).sort(function(a, b) {
    var tda = $(a).find('td:eq(1)').text();
    var tdb = $(b).find('td:eq(1)').text();
    // if a < b return 1
    return tda < tdb ? 1
      // else if a > b return -1
      :
      tda > tdb ? -1
      // else they are equal - return 0    
      :
      0;
  }).appendTo($tbody);
}

$('#firstName').click(function() {
  sortTable("firstName");
});
$('#age').click(function() {
  sortTable("age");
});
$('#date').click(function() {
  sortTable("date");
});
@import 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col" id="firstName">name</th>
      <th scope="col" id="age">age</th>
      <th scope="col" id="date">date joined</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td class="firstName">Mark</td>
      <td>12</td>
      <td>12/02/2006</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td class="firstName">Jacob</td>
      <td>30</td>
      <td>03/04/2018</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td class="firstName">Larry</td>
      <td>22</td>
      <td>07/01/2009</td>
    </tr>
  </tbody>
</table>

エディ

現在、あなたはソートしていますが<td>、これは実際にはrows(<tr>ではなくセルです。

.sortのコールバック関数には2つのパラメータがあります。2つのパラメータを比較する必要があります。

  1. 最初のパラメータを最初に配置する必要がある場合は、負の値を返します。
  2. 2番目のパラメーターを最初に指定する必要がある場合は、正の値を返します。
  3. 位置に変化がない場合は0を返します。

タイプ(数値、テキスト、日付)に基づいてデータを比較する必要があります。テキストの代わりに列のインデックスも使用した方が簡単だと思います。

function sortTable(column, type) {

  //Get and set order
  //Use -data to store wheater it will be sorted ascending or descending
  var order = $('.table thead tr>th:eq(' + column + ')').data('order');
  order = order === 'ASC' ? 'DESC' : 'ASC';
  $('.table thead tr>th:eq(' + column + ')').data('order', order);

  //Sort the table
  $('.table tbody tr').sort(function(a, b) {
  //                                 ^  ^
  //                                 |  | 
  //        The 2 parameters needed to be compared. 
  //        Since you are sorting rows, a and b are <tr>                                 

    //Find the <td> using the column number and get the text value.
    //Now, the a and b are the text of the <td>
    a = $(a).find('td:eq(' + column + ')').text();
    b = $(b).find('td:eq(' + column + ')').text();

    switch (type) {
      case 'text':
        //Proper way to compare text in js is using localeCompare
        //If order is ascending you can - a.localeCompare(b)
        //If order is descending you can - b.localeCompare(a);
        return order === 'ASC' ? a.localeCompare(b) : b.localeCompare(a);
        break;
      case 'number':
        //You can use deduct to compare if number.
        //If order is ascending you can -> a - b. 
        //Which means if a is bigger. It will return a positive number. b will be positioned first
        //If b is bigger, it will return a negative number. a will be positioned first
        return order === 'ASC' ? a - b : b - a;
        break;
      case 'date':
        var dateFormat = function(dt) {
          [m, d, y] = dt.split('/');
          return [y, m - 1, d];
        }

        //convert the date string to an object using `new Date`
        a = new Date(...dateFormat(a));
        b = new Date(...dateFormat(b));

        //You can use getTime() to convert the date object into numbers. 
        //getTime() method returns the number of milliseconds between midnight of January 1, 1970
        //So since a and b are numbers now, you can use the same process if the type is number. Just deduct the values.
        return order === 'ASC' ? a.getTime() - b.getTime() : b.getTime() - a.getTime();
        break;
    }

  }).appendTo('.table tbody');
}

$('#firstName').click(function() {
  sortTable(1, 'text');
});
$('#age').click(function() {
  sortTable(2, 'number');
});
$('#date').click(function() {
  sortTable(3, 'date');
});
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col" id="firstName">name</th>
      <th scope="col" id="age">age</th>
      <th scope="col" id="date">date joined</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td scope="row">1</td>
      <td class="firstName">Mark</td>
      <td>12</td>
      <td>12/02/2006</td>
    </tr>
    <tr>
      <td scope="row">2</td>
      <td class="firstName">Jacob</td>
      <td>30</td>
      <td>03/04/2018</td>
    </tr>
    <tr>
      <td scope="row">3</td>
      <td class="firstName">Larry</td>
      <td>22</td>
      <td>07/01/2009</td>
    </tr>
  </tbody>

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

SQLテーブルを複数の列で並べ替える

分類Dev

Javafxテーブルを複数の列で並べ替える

分類Dev

luaの複数の値でテーブルを並べ替える方法は?

分類Dev

Q:Luaで数値のテーブルを並べ替える

分類Dev

複数のHTMLテーブルを複数の並べ替えで並べ替える

分類Dev

Word:複数のテーブルを選択し、列で並べ替えます

分類Dev

MYSQLビューで複数の類似テーブルを並べ替える

分類Dev

jqueryでテーブルの列の位置を並べ替える方法

分類Dev

データテーブルでのみ数値を持つ列を並べ替える方法は?

分類Dev

特定の値を持つ列の数でテーブルを並べ替える方法

分類Dev

マットテーブルを列の値で並べ替える

分類Dev

Luaの値でテーブルを並べ替える方法は?

分類Dev

テーブルの行を列で並べ替える

分類Dev

テーブルの行を列で並べ替える

分類Dev

複数の列を数値で並べ替える

分類Dev

SQLテーブルを別のテーブルの値で並べ替える

分類Dev

Jqueryはテーブルデータを数値で並べ替えます

分類Dev

phpサブキー値で複数のレイヤーの深さの多次元配列を並べ替える

分類Dev

jQueryテーブルの並べ替えは、列で並べ替えられた色を変更します。

分類Dev

複数のmysqlテーブルの結果を表示して並べ替える

分類Dev

AngularJStheaderを介して複数のテーブルを並べ替える

分類Dev

特定の形式で特定の列を並べ替えてテーブルを並べ替える方法

分類Dev

文字列とbashの数値が混在する列に基づいてテーブルを並べ替える

分類Dev

複数のフィールド(数値に最も近い)で配列を並べ替える

分類Dev

SQLite複数のテーブルを少ないCOUNTで並べ替えます

分類Dev

複数のテーブル行を一度に並べ替えるJqueryUI

分類Dev

複数の列に基づいてprime-uiデータテーブルを並べ替える方法

分類Dev

「TableId」で同じ関数を持つ複数のテーブルを並べ替える方法は?

分類Dev

文字列を数値としてデータテーブルで並べ替える

Related 関連記事

  1. 1

    SQLテーブルを複数の列で並べ替える

  2. 2

    Javafxテーブルを複数の列で並べ替える

  3. 3

    luaの複数の値でテーブルを並べ替える方法は?

  4. 4

    Q:Luaで数値のテーブルを並べ替える

  5. 5

    複数のHTMLテーブルを複数の並べ替えで並べ替える

  6. 6

    Word:複数のテーブルを選択し、列で並べ替えます

  7. 7

    MYSQLビューで複数の類似テーブルを並べ替える

  8. 8

    jqueryでテーブルの列の位置を並べ替える方法

  9. 9

    データテーブルでのみ数値を持つ列を並べ替える方法は?

  10. 10

    特定の値を持つ列の数でテーブルを並べ替える方法

  11. 11

    マットテーブルを列の値で並べ替える

  12. 12

    Luaの値でテーブルを並べ替える方法は?

  13. 13

    テーブルの行を列で並べ替える

  14. 14

    テーブルの行を列で並べ替える

  15. 15

    複数の列を数値で並べ替える

  16. 16

    SQLテーブルを別のテーブルの値で並べ替える

  17. 17

    Jqueryはテーブルデータを数値で並べ替えます

  18. 18

    phpサブキー値で複数のレイヤーの深さの多次元配列を並べ替える

  19. 19

    jQueryテーブルの並べ替えは、列で並べ替えられた色を変更します。

  20. 20

    複数のmysqlテーブルの結果を表示して並べ替える

  21. 21

    AngularJStheaderを介して複数のテーブルを並べ替える

  22. 22

    特定の形式で特定の列を並べ替えてテーブルを並べ替える方法

  23. 23

    文字列とbashの数値が混在する列に基づいてテーブルを並べ替える

  24. 24

    複数のフィールド(数値に最も近い)で配列を並べ替える

  25. 25

    SQLite複数のテーブルを少ないCOUNTで並べ替えます

  26. 26

    複数のテーブル行を一度に並べ替えるJqueryUI

  27. 27

    複数の列に基づいてprime-uiデータテーブルを並べ替える方法

  28. 28

    「TableId」で同じ関数を持つ複数のテーブルを並べ替える方法は?

  29. 29

    文字列を数値としてデータテーブルで並べ替える

ホットタグ

アーカイブ