tags:

views:

33

answers:

1

I have a column within which are multiple 'records' (each a div). Each record has a bunch of fields (each a span whose id is the fieldname).

I want to allow the user to sort all the records based on a field. I also want, the field that has been sorted to be moved to the beginning of the record. So I came up with this. But its really slow for a large sets. Not sure whats the best way to do this. Any ideas?

$(".col1 div").sort(
  function (a,b)
  {
     if($(a).children("."+field).text() > $(b).children("."+field).text())
          return -1;
     else
           return 1;
  }).appendTo(".col1");
+1  A: 

It would make more sense to extract your data into javascript objects and then reorder/render the table with the new sort order. You could make one pass (or serialize your data into a json object directly on the page when you render it out server side) that pulls your data into objects.

data = []
$.each("div",function(i,node){
    var x = $(node);
    data.push({name:x.find(".name"),field:x.find(".field")});
})

// sort the data
sorted = data.sort(function(a,b){ return a['field'] > b['field'] });
// then either rewrite the dom or reorder the dom using the id of each div.

Dom lookups are really expensive, sorting in code will be much faster.

Michael
Makes sense. Need to try this out. Thanks!
Klerk