I have tried to sort the javascript array which is having "order" as the key but it is sorting only the parent array and inner objects are not sorting
Here is my sample code which have tried,
Sample JSON response:
var MainObj = [
{
"title": "Merchant2",
"order": 2,
"subMenu": [
{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
},
{
"title": "Merchant1",
"order": 1,
"subMenu": [
{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
}
]
And below is the sort functionality,
var MainObj = [{
"title": "Merchant2",
"order": 2,
"subMenu": [{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
},
{
"title": "Merchant1",
"order": 1,
"subMenu": [{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
}
]
var sort = function(prop, arr) {
prop = prop.split('.');
var len = prop.length;
arr.sort(function(a, b) {
var i = 0;
while (i < len) {
a = a[prop[i]];
b = b[prop[i]];
i++;
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return arr;
};
console.log(sort('order', MainObj));
But the expected output should be in the below way,
[
{
"title": "Merchant",
"order": 1,
"subMenu": [
{
"subMenu1": "Initiate1",
"order": 1
},
{
"subMenu1": "Initiate2",
"order": 2
},
]
}
]