Reputation: 7625
I have a list of items in a <ul>
:
<li data-number="1"> Pierce </li>
<li data-number="2"> Annie </li>
<li data-number="3"> Jeff </li>
<li data-number="4"> Abed </li>
<li data-number="5"> Britta </li>
Actually, the list is much longer with real data, but bear with me. As you can see, the <li>
elements are listed in numerical order. However, I need to rearrange them to fit a specified order in an array:
Array(2, 3, 1, 5, 4)
How do I do this? If sorted by the array above, the elements should be like the following:
<li data-number="2"> Annie </li>
<li data-number="3"> Jeff </li>
<li data-number="1"> Pierce </li>
<li data-number="5"> Britta </li>
<li data-number="4"> Abed </li>
This seems simple, but I've looked up every jQuery method in the book and I can't figure out how to do this. Thanks a ton for any help in advance.
The specified order is dynamic. However, the elements are always initially listed in numerical order.
Upvotes: 2
Views: 166
Reputation: 150040
A little late, but I'd already written this so it seems a shame to waste it:
var newOrder = ['2', '3', '1', '5', '4'],
$ul = $("ul"),
$lis = $ul.children().remove();
$.each(newOrder, function(key,val){
$ul.append($lis.filter('[data-number="' + val+ '"]'));
});
Demo: http://jsfiddle.net/zgD3n/
Upvotes: 1
Reputation: 39872
Iterate through the array starting at index 1. Then append that item after its preceding element. That's it.
var order = [2, 3, 1, 5, 4];
for (var i = 1; i < order.length; i++) {
$('li[data-number="' + order[i] + '"]').insertAfter($('li[data-number="' + order[i - 1] + '"]'));
}
Or in slightly more readable format
for (var i = 1; i < order.length; i++) {
var curElem = $('li[data-number="' + order[i] + '"]');
var prevElem = $('li[data-number="' + order[i - 1] + '"]');
curElem.insertAfter(prevElem);
}
Upvotes: 2
Reputation: 581
This is going to be a bit rough since I'm not sure of your overall process but I'll give you the gist and you can implement it.
If the key is predefined...
var sort_order = ['2', '3', '1', '5', '4']
$.each(sort_order function(key,value){
// build you list here you can use the value from your sort_order
// to match the data-number and print them out in the order of your choosing.
// this will work if you dynamically create the sort_order as well.
});
The $.each function will work through the sort_order array allowing you to define an order.
Upvotes: 1