views:

30

answers:

2

I need to sort some elements depend on it attribute. For an example:

<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>
+3  A: 

untested...

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

Not sure if that detach() call is required...

Shrikant Sharat
+1  A: 
​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

fantactuka