4

I have a table that looks something like this:

<table>
      <tr id="1">
          <td>bla</td>
      </tr>

      <tr id="2">
          <td>bla</td>
      </tr>

       <tr id="3">
          <td>bla</td>
      </tr>

      <tr id="4">
          <td>bla</td>
      </tr>
</table>

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?

1

2 Answers 2

5

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));
})

http://jsfiddle.net/nZ6HJ/

Sign up to request clarification or add additional context in comments.

11 Comments

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ícioMatté Define "by far". Also, if re-ordering HTML table rows is the task, array loop performance is not the concern.
@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í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 oh thanks for the jsperf =] Yeah, sometimes I have to remember that premature optimization is the root of all evil.
|
2

jsBin demo

for(i=0; i<array.length; i++){
  $('#'+array[i]).appendTo('table');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.