I have a JSON which I am trying to sort based on parent-child relation, I need to sort the JSON such that it should ignore the child and consider only the parent for the sorting but after sorting the child should be always next to its respective parent. In JSON I am using "groupType" to define the parent-child relationship. Here is what I have tried.
Note: We are free to modify the JSON property to define parent-child relationship.
Input
George 279
George_child_a 202
George_child_b 50
Hilary 44
Joe 12
Joe_child_a 22
After sorting alphabatically
Actual Result
Joe_child_a 22
Joe 12
Hilary 44
George_child_b 50
George_child_a 202
George 279
Expected Result alphabetically desc or asc
Joe 12
Joe_child_a 22
Hilary 44
George 279
George_child_b 50
George_child_a 202
Javascript
function sortResults(prop, asc) {
arr.sort(function(a, b) {
if (asc) {
return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
} else {
return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
}
});
renderResults();
}
var arr = [
{
f_name: 'George',
age: 279,
groupType:'A'
},
{
f_name: 'George_child_a',
age: 202,
groupType:'A_1'
},
{
f_name: 'George_child_b',
age: 50,
groupType:'A_2'
},{
f_name: 'Joe',
age: 12,
groupType:'B'
},
{
f_name: 'Joe_child_a',
age: 22,
groupType:'B_1'
},
{
f_name: 'Hilary',
age: 44,
groupType:'C'
}
];