使用jquery进行字母数字排序

时间:2016-12-12 20:48:46

标签: javascript jquery html

我有一个混合数组,我需要按字母顺序排序,然后按数字

排序
[Ab-1,Ab-5,Ab-11,ab-101,ab-100,ab-10,ab-12,ab-3,ab-21]

根据代码,我得到以下输出

ab-1 ab-5 ab-11 ab-101 ab-100 ab-10 ab-12 ab-3 ab-21

根据代码,默认情况下,第三列单独显示活动和非活动。但我想要第一列(ID)也将它排序为:

ab-1
ab-2
ab-3
ab-5
ab-10
ab-11
ab-12
ab-100
ab-101....

请帮助

 <!DOCTYPE HTML>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    // Fetch the values from json
    $(document).ready(function() {  
                        $.getJSON("dynamic_content_values1.json",   

/* sort starts for Active and Inactive */                                       
                                        function(result_1) {

                                        function sortJSON(data, key) {
                                        return data.sort(function (a, b) {
                                        var x = a[key];
                                        var y = b[key];
                                        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
                                        });
                                        }

                                        sorting_active_and_inactive = sortJSON(result_1, 'flag'); 
/* sort End for Active and Inactive*/
                                            $.each(sorting_active_and_inactive,function(i, field) {
                                                var status = field.flag;

                                                if (status == 'N') {
                                                    status = 'Active';
                                                } else {
                                                    status = 'Inactive';
                                                }
                                                var data = '<tr><td><a  href="#">' + field.first_column + '</a></td><td>' + field.summary + '</td><td>' + status + '</td></tr>';
                                                $("#resultBody").append(data);
                                            });
                                        });



    //******************************************* Starting CODE for Sorting the Active/In-Active Columns *******************************************    


                            function sortTable(table, col, reverse) {
                                var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
                                    tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
                                    i;
                                reverse = -((+reverse) || -1);
                                tr = tr.sort(function (a, b) { // sort rows
                                    return reverse // `-1 *` if want opposite order
                                        * (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
                                            .localeCompare(b.cells[col].textContent.trim())
                                           );
                                });
                                for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
                            }

                            function makeSortable(table) {
                                var th = table.tHead, i;
                                th && (th = th.rows[0]) && (th = th.cells);
                                if (th) i = th.length;
                                else return; // if no `<thead>` then do nothing
                                while (--i >= 0) (function (i) {
                                    var dir = 1;
                                    th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
                                }(i));
                            }

                            function makeAllSortable(parent) {
                                parent = parent || document.body;
                                var t = parent.getElementsByTagName('table'), i = t.length;
                                while (--i >= 0) makeSortable(t[i]);
                            }

                            window.onload = function () {makeAllSortable();};

//************************************************** Ending CODE for Sorting the Active/In-Active Columns *********************************
                    });



    function showabc() {
        document.getElementById('container1').style.display = "block";
    }
</script>
</head>
<body>
    <div class="" id="container1">
        <table>
            <thead>
                <tr>
                    <th><b>ID</b></th>
                    <th><b>Summary</b></th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody id="resultBody" style="cursor: move">
            </tbody>
        </table>
    </div>
    <div class="containerPopup1"><div id="abc1" style="height: 1400px;"></div></div>
    <div  class="containerPopup"><div id="abc2" style="height: 2700px;"></div></div>
</body>
</html>

Json结构:dynamic_content_values1.json

[ {
    "first_column": "AB-1",
    "summary": "AB-1 Summary",
    "flag": "N"
}, {
    "first_column": "AB-11",
    "summary": "AB-11 Summary",
    "flag": "N"
},{
    "first_column": "AB-12",
    "summary": "AB-12 Summary",
    "flag": "Y"
},{
    "first_column": "AB-10",
    "summary": "AB-10 Summary",
    "flag": "Y"
},{
    "first_column": "AB-100",
    "summary": "AB-100 Summary",
    "flag": "Y"
},{
    "first_column": "AB-101",
    "summary": "AB-101 Summary",
    "flag": "N"
},{
    "first_column": "AB-2",
    "summary": "AB-2 Summary",
    "flag": "Y"
},{
    "first_column": "AB-3",
    "summary": "AB-3 Summary",
    "flag": "Y"
},{
    "first_column": "AB-21",
    "summary": "AB-21 Summary",
    "flag": "Y"
},{
    "first_column": "AB-210",
    "summary": "AB-210 Summary",
    "flag": "Y"
},{
    "first_column": "AB-211",
    "summary": "AB-211 Summary",
    "flag": "Y"
},{
    "first_column": "AB-5",
    "summary": "AB-5 Summary",
    "flag": "N"
}]

2 个答案:

答案 0 :(得分:0)

稍微改变你的逻辑,看看它是否最适合你,将值拆分为-,然后以单独的方式比较数字和字符串。您可以添加NaN条件,为简单起见,我将其跳过。

工作片段:

&#13;
&#13;
function naturalSorter(as, bs) {
  var splittedA = as.split("-");
  var splittedB = bs.split("-");
  if (splittedA[0].toLowerCase() > splittedB[0].toLowerCase()) {
    return 1
  } else if (splittedA[0].toLowerCase() < splittedB[0].toLowerCase()) {
    return -1;
  } else {
    return Number(splittedA[1]) === Number(splittedB[1]) ? 0 : Number(splittedA[1]) > Number(splittedB[1]) ? 1 : -1;
  }
}

$(document).ready(function() {
  var selectModel = [];

  $('table.table_sorting td').each(function() {
    var $this = $(this);
    selectModel.push({
      value: $this.val(),
      text: $this.text()
    });
  });

  selectModel.sort(function(a, b) {
    return naturalSorter(a.text, b.text);
  });

  var tempHtml = '';

  for (var i = 0, ii = selectModel.length; i < ii; i++) {
    //tempHtml += '<option value="' + selectModel[i].value + '">' + selectModel[i].text + '</option>';
    tempHtml += '<tr><td>' + selectModel[i].text + '</td></tr>';
  }

  $('table.table_sorting').html(tempHtml);

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="border: 1px solid red;" class="table_sorting">
  <tr>
    <td>ab-1</td>
  </tr>
  <tr>
    <td>ab-11</td>
  </tr>
  <tr>
    <td>ab-12</td>
  </tr>
  <tr>
    <td>ab-13</td>
  </tr>
  <tr>
    <td>ab-100</td>
  </tr>
  <tr>
    <td>ab-101</td>
  </tr>
  <tr>
    <td>ab-102</td>
  </tr>
  <tr>
    <td>ab-111</td>
  </tr>
  <tr>
    <td>ab-222</td>
  </tr>
  <tr>
    <td>ab-333</td>
  </tr>
  <tr>
    <td>ab-3</td>
  </tr>
  <tr>
    <td>ab-2</td>
  </tr>
  <tr>
    <td>ab-4</td>
  </tr>
  <tr>
    <td>ab-44</td>
  </tr>
  <tr>
    <td>ab-5</td>
  </tr>
  <tr>
    <td>ab-55</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于排序,您可以使用简化的链式方法,如果前者重新为零,则需要进行组合处理。

&#13;
&#13;
var data = ['Ab-1', 'Ab-11', 'Ab-12', 'ab-10', 'ab-100', 'ab-101', 'ab-2', 'ab-3', 'ab-105'];

data.sort(function (a, b) {
    var aa = a.split('-'),
        bb = b.split('-');
    return aa[0].toLowerCase().localeCompare(bb[0].toLowerCase()) || aa[1] - bb[1];
});

console.log(data);
&#13;
&#13;
&#13;