Jquery sort element with array value

I need to sort some elements depending on this attribute. For instance:

<div id="sort"> <div n="1"></div> <div n="2"></div> <div n="3"></div> <div n="4"></div> </div> 

And array_num

 {3, 2, 1, 4} 

pseudo code:

 $('#sort').sort(array_num, 'n'); 

Results will be:

 <div id="sort"> <div n="3"></div> <div n="2"></div> <div n="1"></div> <div n="4"></div> </div> 
+4
source share
4 answers
 var order = [3, 2, 4, 1]​; var el = $('#sort'); var map = {}; $('#sort div').each(function() { var el = $(this); map[el.attr('n')] = el; }); for (var i = 0, l = order.length; i < l; i ++) { if (map[order[i]]) { el.append(map[order[i]]); } } 

Full code here

+7
source

untested ...

 $.fn.asort = function (order, attrName) { for(var i = 0, len = order.length; i < len; ++i) { this.children('[' + attrName + '=' + order[i] + ']').appendTo(this); } } 
+5
source

I came across this, trying to fix what happened after. I applied the @ shrikant-sharat method and added a little to it, since the attribute that I need for sorting was actually a child. Thought I'd add here if that helps anyone (and for the future me!)

 $.fn.asort = function (order, attrName, filter) { console.log(this.length, order.length, order); for(var i = 0, len = order.length; i < len; ++i) { if(typeof(filter) === 'function') { filter(this.children(), attrName, order[i]).appendTo(this); } else { this.children('[' + attrName + '=' + order[i] + ']').appendTo(this); } } return this.children(); } 

It allows you to pass a filter function according to the element you are using. This is not the most efficient, I suppose, but it works for me, for example:

 $('.my-list').asort(mapViewOrder, 'data-nid', function(items, attrName, val) { return items.filter(function(index, i) { return ($(i).find('[' + attrName + '="' + val + '"]').length); }); }); 
0
source

However, I think there may be a new way to sort them without an attribute, but I cannot get it to work properly

 var order = [4,3,2,7,5,0,1,6,8]; var i = 0; $.fn.formordina = function(selector){ (selector ? this.find(selector) : this).parent().each(function(){ $(this).children(selector).sort(function(){ return order[i++]; }).detach().appendTo(this); }); return this; }; $(".form-action ol").formordina('li'); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script> <div class="form-action"> <ol> <li>banana</li> <li>apple</li> <li>tomato</li> <li>kiwi</li> <li>pear</li> <li>peach</li> <li>lemon</li> <li>ginger</li> <li>orange</li> </ol> </div> 
0
source

All Articles