/*
I have two people
*/
var person_one= 'person_one';
var person_two= 'person_two';
/*
This is a response I get from a server
*/
var response = [
{"key":{"name":"person_one","kind":"attrA","path":["attrA","person_one"]},"data":{"q":"3","n":"0"}},
{"key":{"name":"person_one","kind":"attrB","parent":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"path":["attrA","person_two","attrB","person_one"]},"data":{"some_data":"p"}},
{"key":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"data":{"q":"1","n":"0"}}
];
/*
Sort the object array by the key.kind field. So all attrA will come first and then attraB
*/
function compare(a,b) {
if (a.key.kind < b.key.kind )
return -1;
else if (a.key.kind > b.key.kind)
return 1;
else
return 0;
}
response.sort(compare); //sort
console.log('Sorted response = ' + JSON.stringify(response) ); //print sorted response
This is the code I have so far. What is happening is I get a response from the server which is:
[
{"key":{"name":"person_one","kind":"attrA","path":["attrA","person_one"]},"data":{"q":"3","n":"0"}},
{"key":{"name":"person_one","kind":"attrB","parent":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"path":["attrA","person_two","attrB","person_one"]},"data":{"some_data":"p"}},
{"key":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"data":{"q":"1","n":"0"}}
]
I need to now sort this response using two following conditions:
The first condition is to sort it by the key.kind attribute which the code does. All
attraAwill need to show first, thenattraBThe second condition is after this is sorted by key.kind it then needs to sort it by name. So that person_one will always come before person_two (these are just fake names to show the concept, but actual names could be like jack or jill, etc). So I am able to sort by key.kind, but I am unsure how to add a second sort condition now and sort it by it. If this was SQL it would be similar to something such as this:
SELECT * FROM table ORDER BY KIND,NAME; -- sort by KIND first then NAME
var person_one= 'person_one'; var person_one = 'person_two';should probably be fixed.