0

I need to sort the list ascending or descending with ID value of the LI tag once I click the sort button. If it is in ascending order, it must sort to descending and vice versa.

eg:

 <ul id="place-list">
      <li id="0">Paris</li>
      <li id="1">greece</li>
      <li id="2">London</li>
 </ul>

I need to sort it without using the tsort function in jQuery-tinysort. How can I do this?

Shoe
  • 74,840
  • 36
  • 166
  • 272
user2014494
  • 21
  • 1
  • 1
  • 3
    StackOverflow is not a "write my code for me" site. It's a "help me with the code I've written" site. – Raymond Chen Jan 26 '13 at 22:27
  • This: http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery – Tomer Arazy Jan 26 '13 at 22:27
  • Don't use numbers for IDs. Not only are they hard to keep unique, they're also non-standard in HTML4 and in my opinion dubious in HTML5. – Niet the Dark Absol Jan 26 '13 at 22:27
  • possible duplicate of [Sort element by numerical value of data attribute](http://stackoverflow.com/questions/14160498/sort-element-by-numerical-value-of-data-attribute) – Felix Kling Jan 26 '13 at 22:33
  • I think it's a fair question if new, though need to know if new to jquery or javascript in general to be able to give a good answer – Rob Sedgwick Jan 26 '13 at 22:37

4 Answers4

3

Don't use jQuery when it isn't needed.

function sortList() {
    sortList.direction = sortList.direction ? false : true;
    var arr = [], list = document.getElementById('place-list'),
        c = list.children, l = c.length, i;
    for(i=0; i<l; i++) arr[i] = c[i]; // "convert" NodeList to array
    arr.sort(function(a,b) {return a.id < b.id ? -1 : 1;}); //sorting function ends here.
    if( !sortList.direction) arr = arr.reverse();
    for(i=0; i<l; i++) list.appendChild(arr[i]);
};
Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

Can use sort() on collection of jQuery elements:

var $list = $('#place-list');    
/* store lastSort direction in button data*/
$('button').data('lastSort', 'asc').click(function() {
    var $btn=$(this), $items = $list.children(), lastSort=$btn.data('lastSort');
    var direction = lastSort=='asc' ? 'desc' :  'asc';
   $btn.data('lastSort',direction);
    $list.empty().append($items.sort(directionSort[direction]));
});


var directionSort = {
    asc: function (a, b) {
        return a.id < b.id ? -1 : 1;
    },
    desc: function (a, b) {
        return a.id > b.id ? -1 : 1;
    }
}

DEMO: http://jsfiddle.net/XAutV/1/

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • this is fab, but if the id is numeric, it assumes the id is a string rather than an integer, and sorts it as follows: 1,10,11,12,13,14, 15, 16, 17,18,19,2,20, and so on, so you need to change `a.id` to `parseInt(a.id)` and `b.id` to `parseInt(b.id)` – Yvonne Aburrow May 23 '17 at 13:33
1

I added a #sort element that can be clicked to sort the elements

$("#sort").click(function(){
    var sortedLis = [];
    var lis = $("#place-list").find("li");
    lis.remove();

    var descending = $(lis[0]).attr("id") == lis.length -1;
    lis.each(function(index, element){
        if(!descending){
          sortedLis[lis.length - $(element).attr("id")] = element;
        }else{
            sortedLis[$(element).attr("id")] = element;
        }
    });

    $("#place-list").append(sortedLis);
});

Example

Thirumalai murugan
  • 5,698
  • 8
  • 32
  • 54
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

You also could use .map()

Also I would change id="" to data-id="".

HTML

<ul id="place-list">
    <li data-id="4">Tokyo 4</li>
    <li data-id="0">Paris 0</li>
    <li data-id="5">Frankfurt 5</li>
    <li data-id="2">London 2</li>
    <li data-id="1">greece 1</li>
    <li data-id="3">Munich 3</li>
</ul>
<button id="asc">ASC</button>
<button id="desc">DESC</button>

jQuery

var sortArray = function (items, inverse) {
    var inverse = inverse || false;

    var sortedArray = items.map(function () {
        return {
            id: $(this).data("id"),
            element: $(this)[0].outerHTML
        };
    });

    var appendTo = items.parent();
    items.remove();

    sortedArray.sort(function (a, b) {
        return a.id > b.id ? (inverse ? -1 : 1) : (inverse ? 1 : -1);
    });

    sortedArray.each(function () {
        $(appendTo).append(this.element);
    });
}

$("#asc").click(function () {
    sortArray($("#place-list").find("li"));
});

$("#desc").click(function () {
    sortArray($("#place-list").find("li"), true);
});

Example

http://jsfiddle.net/995dY/

Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82