Take the 2-minute tour ×

I have a table that looks something like this:

      <tr id="1">

      <tr id="2">

       <tr id="3">

      <tr id="4">

I also got an array according to which I should sort this table rows, say array goes something like

array= [3, 4, 1, 2];

Any tips or ideas how I can rearrange rows with jquery/javascript to match the array?

share|improve this question
possible duplicate: JQuery/Javascript Reordering rows –  Andreas Sep 2 '12 at 22:40
add comment

2 Answers

up vote 3 down vote accepted

Append them again, in the order you need them to be in. When you call .append and the element is already visible it will be removed from its current location.

var order = [3,2,1,4];

$.each(order, function(){
  $("table").append($("#" + this));


share|improve this answer
By far the simplest and most effective solution (assuming all row IDs are in the array). Using $.each to iterate a simple array is slightly overkill though, I'd use a simple for loop if performance is a concern. –  Fabrício Matté Sep 2 '12 at 22:47
@FabrícioMatté Define "by far". Also, if re-ordering HTML table rows is the task, array loop performance is not the concern. –  Tomalak Sep 2 '12 at 22:51
@Tomalak Sorry, I guess I didn't pay enough attention when reading your answer. But I'll defend my performance statement, just because you're carrying 10 elephants on your back doesn't mean that you have to carry 1 more unnecessarily - they will add up with time as your application grows. And I find a for loop more readable and it doesn't a create a closure unnecessarily either. –  Fabrício Matté Sep 2 '12 at 22:55
@FabrícioMatté No, my answer was actually wrong, that's why I deleted it. Regarding your analogy: If reordering table rows is 10 elephants, the $.each() is an ant. You won't gain any performance to speak of from not using it. –  Tomalak Sep 2 '12 at 23:00
@Tomalak oh thanks for the jsperf =] Yeah, sometimes I have to remember that premature optimization is the root of all evil. –  Fabrício Matté Sep 2 '12 at 23:24
show 6 more comments

jsBin demo

share|improve this answer
add comment

Your Answer


