I need to sort a JSON array by a value which is nested. Here is the routine I am using and it always returns 0
. The field value I want to sort on is advancedoptions.storeId
.
orders.sort(GetSortOrder("advancedOptions.storeId"));
function GetSortOrder(prop) {
return function(a, b) {
if (a[prop] > b[prop]) {
return 1;
} else if (a[prop] < b[prop]) {
return -1;
}
return 0;
}
}
I want to sort the JSON by storeId:
{
"orders": [
{
"orderId": 415354051,
"advancedOptions": {
"storeId": 376480
}
},
{
"orderId": 415172626,
"advancedOptions": {
"storeId": 375780
}
},
{
"orderId": 414286558,
"advancedOptions": {
"storeId": 376480
}
},
{
"orderId": 412403726,
"advancedOptions": {
"storeId": 376480
}
}
]
}
Correct sort order should be:
"orderId": 415172626,
"orderId": 415354051,
"orderId": 414286558,
"orderId": 412403726,