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!