views:

35

answers:

1

I am loading some XML data, building it into an unordered list and displaying it. I now need to sort this data so it is displayed in a random order each time it is loaded. Do I need to completely change how I am doing this below or is there an easy way to get the data and sort it before using my existing code to format it for output?

Here is the straight load and display code:

var out = '<li>';
$(xml).find('person').each(function(){
    counter++;

    var person_image   = $(this).find('person_image').text();
    var person_name    = $(this).find('person_name').text();
    var person_title   = $(this).find('person_title').text();
    var person_company = $(this).find('person_company').text();

    out = out + '<div><a href="foo/'+ belongsTo +'.php#'+ person_image +'"><img src=/images/' + belongsTo + '/' + person_image + '.jpg />' + '<br /><label><span>' + person_name + '</span><br />' + person_title + '<br />' + person_company + '</label></a><br /></div>';

    if(counter % 3 === 0 && counter !== total){
        out = out + '</li><li>';
    }
});
out = out + '</li>';
$('#display_block').html(out);

As you can see I am building the list items as I load them, in the order they are retrieved from the XML... this is what I need to randomly sort. I suppose I need to get everything first (into an array? Associative array? Object? Not sure how to best do this), randomly sort it and then iterate through building my out variable?

How would I do what I'm doing above but stick some sort of random sorting in the process?

As for randomly sorting, I came up with the following which seems to work:

function randomsort(a, b){ a=Math.random(); b = Math.random(); return a - b }

Just need to know how to gather the data so i can apply this sorting. Thanks!

+1  A: 

You could create a seperate array of the same length as the number of "person" elements in your XML. Fill this array with the keys to the XML elements (0 to n) and randomly sort it using your function. Then simply keep shifting items off this array and use the values you get to access the collection of XML elements.

That way, you won't have to manipulate the XML data (destroying the original structure) and keep most of the code you already have.

Victor Welling
I ended up creating an array with one key for each element (as you suggested) then creating arrays as the value on each of those keys that contained the needed values (so array(0=>array(0=>"content",1=>"more"),1=>array(0=>"foo",1=>"bar"))). After that I did the random sort and then iterated over it with a for loop, outputting what I needed. Works great.
rg88