A: 

Your questions are very difficult to answer without knowing exaclty the reasons you're doing this!

Anyway, in attempting to answer, 1) :

  • If you are generating a list in HTML on the server anyway, and the order of the list doesn't change, why do it with JSON & JavaScript? Use your server side tech to do this.

  • If the list will change and you want something in the UI on the client to manage the order of the list and you have accessibility considerations: create your list and your JSON using your server side tech, order both server side and then render your HTML list and pass your JSON to the client. This will make the list available to client (user) without JavaScript enabled and the 'sortable list' available to JavaScript enabled clients.

  • If you don't have any concern for users without JavaScript AND the list needs to be reorderable then just pass your JSON data to your client and use JavaScript to render it and handle the reordering.

2) I'm assuming that each of your objects that you want to sort is in an array? If they are then I would use the Array.sort method : www.w3schools.com/jsref/jsref_sort.asp

Something like the following should give you an idea of how to go about doing this:

       var data = [{
    "Topic" : "C",
    "Examples":[
     {"Example" : "Example A one"},
     {"Example" : "Example A two"},
    ] 
   },{
    "Topic" : "B",
    "Examples":[
     {"Example" : "Example B one"},
     {"Example" : "Example  B two"},
    ] 
   },{
    "Topic" : "A",
    "Examples":[
     {"Example" : "Example C one"},
     {"Example" : "Example C two"},
    ] 
   }];

   function sortTopics(topics, firstItem){
    var sortedArray = []; 

    for (var i = 0; i < topics.length; i++) {
     if (topics[i].Topic == firstItem) {
      //add the specified first item
      sortedArray.push(topics[i]);
      //remove element from original
      topics.splice(i,1);
break;
     }

    }

    //sort the remainder of the array
    topics.sort(function(a,b){
     if(a.Topic < b.Topic){return -1;}
     if(a.Topic > b.Topic){return 1;}
     return 0;
    });

    //loop though and add each item to the new array          
    for (var i = 0; i < topics.length; i++) {
     sortedArray.push(topics[i]);
    }

    return sortedArray;
   }

   sortTopics(data, "C");

I'm not sure how cross browser it would be and obviously you'll need to generate the list from the JSON but it should give you somewhere to start, you could make it all more generic and efficient of course!

Good luck.

Lewis
Great code example - thank you for devoting your time.I was never really generating the html server side but maybe I should?Somehow it feels more flexible to output everything in JSON and do the sorting etc. client side. Hmm, bad approach?
dani
ps. Typo: the "break;" should go inside the if-statement.
dani