0

I have a mixed array that i need to sort by alphabet and then by digit

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

As per the code, im getting the below output

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

As per the code, by default third column is displaying seperately for active and inactive. But i want first column(ID) also to sort it to be:

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

Any help please

 <!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 Structure: 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"
}]
karthik
  • 23
  • 1
  • 6
  • You should check this post: [JavaScript Natural Sort](http://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings) – Wichard Riezebos Dec 12 '16 at 20:57
  • @WichardRiezebos Looks likes OPs code comes directly from the second answer.... lol – epascarello Dec 12 '16 at 20:59
  • The two orders seem like they are the same... was that a typo? Do you want rows, not cells? – epascarello Dec 12 '16 at 21:01
  • Your desired output is in the same order as what you're getting. It looks like your problem is just with how you're formatting the result, not with the sorting. – Barmar Dec 12 '16 at 21:01
  • You need to put each value into a separate `...`, not just `...` – Barmar Dec 12 '16 at 21:02

2 Answers2

0

Changed your logic a little, see if it best fits you, split the value at - and then compare number and string in seprate manner. You may add NaN condition, I skipped it for simplicity.

Working Snippet:

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);

});
<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>
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32
  • Its working fine. having one more query. this is working only for first column. Suppose if i have 3 columns in all the rows, then it is not working. i Want to do this sorting only for first column. can you please help this. – karthik Dec 13 '16 at 20:23
  • @karthik : Is it dynamic data that you are loading in the table or the table is already present and you need to sort it? The data you are displaying in the table is it stored in a variable or not? – Ajay Narain Mathur Dec 14 '16 at 02:23
  • @AJ- Yes this is dynamic data. Actually im getting the value from json file and displaying it in GUI. All these values are displaying in column1. – karthik Dec 14 '16 at 03:59
  • @karthik : In this case I will suggest sort the json and then load the result in the table. Maybe share your json structure, I will help you create the, please join **sort-json - javascript** on stackoverflow chat. – Ajay Narain Mathur Dec 14 '16 at 04:06
0

For sorting, you could use a simplified chained approach which takes a comnparisond an proceed if the former reuslt is zero.

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392