Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery sort element with array value

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>
like image 389
StoneHeart Avatar asked Dec 13 '22 20:12

StoneHeart


1 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 ​

like image 92
fantactuka Avatar answered Jan 05 '23 23:01

fantactuka