Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

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

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

Each column sort by clicking in every header tag and currently the sort is alphabetical but I need the sort will be numeric or alphabetical or date regardless of it. The data is a Json that come from the other side and could have numeric or alphabetical or date column.

This is my sort code:

function sortMainTable(_num) {
  var table, rows, sw, i, x, y;
  table = document.getElementById("mainTable");
  sw = true;
  while (sw) {
    sw = false;
    rows = table.getElementsByTagName("tr");
    for (i = 1; i < (rows.length - 1); i++) {
      x = rows[i].getElementsByTagName("td")[_num];
      y = rows[i + 1].getElementsByTagName("td")[_num];
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        sw = true;
        break;
      }
    }
  }
}

Example :

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",
  },
]

As I told above, I need the sort will be numeric or alphabetical or date regardless of it. (if the column is numeric, the table sort is order by numeric column, and if the column is alphabetical, the table sort is order by alphabetical column, if the column is date, the table sort is order by date column)

Any idea?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...