Q:

Sort an array based on multiple strings

I have a JSON array that looks like this:
var all_messages = [{
  name: 'user1',
  replying_to: '',
  message: 'xxxxx'
},
{
 name: 'user3',
 replying_to: 'user4',
 message: 'xxxxx'
},
{
  name: 'user2',
  replying_to: 'user1',
  message: 'xxxxxx'
},
{
  name: 'user5',
  replying_to: '',
  message: 'xxxxxx'
},
{
  name: 'user1',
  replying_to: 'user2',
  message: 'xxxxx'
}]

I would like to use Javascript to reorder this array based on name and replying_to so that the order of objects looks like a conversation thread. Ideally, the array would have replies directed to the user underneath their name, and messages directed at no specific user would be at the end of the array. In other words, I want the array to look like this:
var sorted_messages = [{
  name: 'user1',
  replying_to: '',
  message: 'xxxxx'
},
{
  name: 'user2',
  replying_to: 'user1',
  message: 'xxxxx'
},
{
  name: 'user1',
  replying_to: 'user2',
  message: 'xxxxxx'
},
{
 name: 'user3',
 replying_to: 'user4',
 message: 'xxxxx'
},
{
 name: 'user5',
 replying_to: '',
 message: 'xxxxx'
}]

So far I have tried creating a nested for loop to check for a name match but I am stuck in trying to get the loop to work. Another problem with this loop is that if one person replies to another person more, it stops updating the array properly and starts duplicating messages.
var names = [];
var sorted_comments = [];
//extract names to use for filter
for (var i = 0; i < all_messages.length; i++) {
    names.push(all_messages[i].name);
    //apply code to remove duplicate names...
}

for (var i = 0; i < all_messages.length; i++) {
    for (var j = 0; j < names.length; j++) {
        if (names[j] == all_messages[i].name) {
           sorted_comments.push(all_messages[i]);
         } else if (names[j] == all_messages[i].replying_to) {
           sorted_comments.push(all_messages[i])
         }
     }
}

What is an elegant way of achieving this kind of filtering?

A:

Try this
var sorted_messages = all_messages.sort(function(a,b){
    return a.name > b.name && a.replying_to >= b.name
})

