Search code examples
jquerysortingjquery-ui-droppable

Javascript sorting by numeric hierachy (extracted from div)


I have a set of divs that have been cloned via Jquery ui Draggable/ Droppable.

The original elements have numeric IDs (1,2,3, etc.), which determines their hierarchy. Cloned element IDs are appended with the prefix "clone_" so that they remain unique:

<div id="parent">
    <div id="clone_1" class="clone">foo</div>
    <div id="clone_3" class="clone">roo</div>
    <div id="clone_2" class="clone">bar</div>
</div>

My question is, how can I sort the cloned items numerically according to their hierarchy? I can find the number:

var cloneID = $('.clone').attr('id');
var IDstring = cloneID.split("_"); 
var hierarchy = IDstring[1];

But I can't figure out the next step. Thanks.


Solution

  • function getarr(a){
    var IDstr2 =[];
    
    for (var i=1;i<a.length;i=i+2){
     IDstr2.push(a[i]);
    
    }
    return IDstr2;
    }
    
    var x = getarr(IDstring);
    
     x.sort(function(a,b){return a-b;});
    

    or descending order: x.sort(function(a,b){return b-a;});