Sort Table by click in header tag regardless of it is numeric, alphabetical or date

后端 未结 2 374
悲&欢浪女
悲&欢浪女 2020-12-12 06:48

I\'m trying to sort my table by javascript(only javascriptpure, not library and not framework, only javascriptpure).

Each column sort by clicking in every header tag

相关标签:
2条回答
  • 2020-12-12 07:23

    What you want is most likely a natural sort. Where you can sort on alphanumerics, "naturally". There are a myriad of options out there on npm that you can use as reference. The first hit on google is javascript-natural-sort. This should point you in the right direction.

    Once you have that, I would bind an event handler to your table header, which passes along the column name you wish to .sort() on, then natural sort your places array based on that key, then rerender the table.

    0 讨论(0)
  • 2020-12-12 07:25

    In JavaScript you can sort arrays of objects by using native Array.sort().

    The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

    Parameters

    compareFunction Optional Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

    Return value

    The sorted array. Note that the array is sorted in place, and no copy is made.

    In your places variable, you have to compare:

    • Strings: By using > or < sign, in the compare function.
    • Numbers: By using - sign, in the compare function.
    • Dates: You can convert string date (02/12/2015) to the timestamp equivalent (1423717200000) by using: new Date("02/12/2015").getTime(). So you can use - sign, in the compare function.

    I've rewrite your code to:

    1. Render the table with the places variable data, dynamically without ordering.
    2. Render the data when it is sorted or not.
    3. Set the ordering control in the headers.
    4. Write a helper function to sort arrays according key, data and type parameters. Returns the sorted data.

    (function() {
      var places = [{
        "city": "Los Angeles",
        "country": "USA",
        "price": "130.90",
        "date": "02/12/2015"
      }, {
        "city": "Boston",
        "country": "USA",
        "price": "11.40",
        "date": "10/04/2014",
      }, {
        "city": "Chicago",
        "country": "USA",
        "price": "320.40",
        "date": "06/05/2017",
      }];
    
      // 4.
      function sortByKey(key, data, type) {
        if (key === "price") {
          if (type === "asc") { // ↑
            data.sort(function(a, b) {
              return (a[key] * 1) > (b[key]);
            });
          } else { // ↓
            data.sort(function(a, b) {
              return (a[key] * 1) < (b[key]);
            });
          }
        } else if (key === "date") {
          if (type === "asc") {
            data.sort(function(a, b) {
              return new Date(a[key]).getTime() - new Date(b[key]).getTime();
            });
          } else {
            data.sort(function(a, b) {
              return new Date(b[key]).getTime() - new Date(a[key]).getTime();
            });
          }
        } else {
          if (type === "asc") {
            data.sort(function(a, b) {
              return a[key] > b[key];
            });
          } else {
            data.sort(function(a, b) {
              return a[key] < b[key];
            });
          }
        }
        return data;
      }
    
      // 3.
      function setSorterControl(data) {
        // Remove the span class after sorting.
        function reset() {
          var elems = document.querySelectorAll("#mainTable th span"), i, len = elems.length, obj;
          for (i = 0; i < len; i++) {
            obj = elems[i];
            obj.removeAttribute("class");
          }
        }
        
        /*
          Render the sorted data in the tbData element.
          Set the data-type attribute with the proper value after click in the header control.
          Set the proper span class when its clicked to sort the data.
         */
        function sorter(e) {
          var tbData = document.getElementById("tbData"), elem = e.target;
          tbData.innerHTML = sortTable(sortByKey(elem.getAttribute("data-key"), data, elem.getAttribute("data-type")));
          elem.setAttribute("data-type", elem.getAttribute("data-type") === "asc" ? "desc" : "asc");
          reset();
          elem.children[0].className = elem.getAttribute("data-type") === "asc" ? "desc" : "asc";
    
        }
        var elems = document.querySelectorAll("#mainTable th"), i, len = elems.length, obj;
        for (i = 0; i < len; i++) {
          obj = elems[i];
          obj.onclick = sorter;
        }
      }
      
      // 1.
      function renderTable(data, type) {
        var html = "", i, header = Object.keys(data[0]), lenHeader = header.length;
        html += "<thead><tr>";
        for (i = 0; i < lenHeader; i++) {
          html += "<th data-key=\"";
          html += header[i];
          html += "\" data-type=\"asc\">";
          html += header[i];
          html += "<span></span></th>";
        }
        html += "</tr></thead><tbody id=\"tbData\">";
        html += sortTable(data);
        html += "</tbody>";
        return html;
      }
    
      // 2.
      function sortTable(data) {
        var html = "",
          i, j, len = data.length,
          header = Object.keys(data[0]),
          lenHeader = header.length;
        for (i = 0; i < len; i++) {
          html += "<tr>";
          for (j = 0; j < lenHeader; j++) {
            html += "<td>";
            html += data[i][header[j]];
            html += "</td>";
          }
          html += "</tr>";
        }
        return html;
      }
      document.getElementById("mainTable").innerHTML = renderTable(places);
      setSorterControl(places);
    })();
    #mainTable {
      border: solid 1px #ccc;
      border-collapse: collapse;
    }
    
    #mainTable th,
    #mainTable td {
      padding: 5px;
    }
    
    #mainTable th {
      background-image: linear-gradient(#bcbebf, #eff3f7);
      cursor: pointer;
    }
    
    #mainTable th span {
      pointer-events: none;
    }
    
    #mainTable th span:before {
      content: "↕";
    }
    
    #mainTable th span.asc:before {
      content: "↑";
    }
    
    #mainTable th span.desc:before {
      content: "↓";
    }
    <table id="mainTable" border="1"></table>

    0 讨论(0)
提交回复
热议问题