I have a JSON array as follows :
[{
"name": "ABC",
"default": false,
"details": [
{
"detail1": "value1"
},
{
"detail2": "value2"
}
]
},
{
"name": "PQR",
"default": false,
"details": [
{
"detail3": "value3"
},
{
"detail4": "value4"
}
]
},
{
"name": "XYZ",
"default": true,
"details": [
{
"detail5": "value5"
},
{
"detail6": "value6"
}
]
}]
Now if the default
value is true
, I want it to be the first element of the array and rest of the elements should be sorted alphabetically based on the name
. Only one of the element will have default
as true
or all the elements will have default
as false
.
The expected JSON after sorting should be :
[{
"name": "XYZ",
"default": true,
"details": [
{
"detail5": "value5"
},
{
"detail6": "value6"
}
]
},
{
"name": "ABC",
"default": false,
"details": [
{
"detail1": "value1"
},
{
"detail2": "value2"
}
]
},
{
"name": "PQR",
"default": false,
"details": [
{
"detail3": "value3"
},
{
"detail4": "value4"
}
]
}]
I have tried this code for sorting the JSON array :
jsonArray.sort( function( a, b ) {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
});
But I am not able to figure out how to check for the default
value and sort accordingly. How do I achieve the expected result?