0

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?

Andy
  • 61,948
  • 13
  • 68
  • 95
AJ31
  • 210
  • 2
  • 13
  • 1
    Before your `return`, try something like `if (a.default) return -1; if (b.default) return 1;` (also note that what you have there is simply an Array. JSON is a text format used to transmit objects, but there's no such thing as a JSON Array / JSON Object) –  Sep 22 '21 at 08:42
  • I'd start by not reassigning your input variables `a, b`, doing this you lose access to other properties of your array elements. – phuzi Sep 22 '21 at 08:43

1 Answers1

0

You're on the right way. Just modify the function to include the check for default:

jsonArray.sort( function( a, b ) {
    const name1 = a.name.toLowerCase();
    const name2 = b.name.toLowerCase();    
    return (b.default - a.default) || ((name1 > name2) - (name2 > name1))
});

I've got the quick code for string comparison from here: https://stackoverflow.com/a/17765169/2244262

Stalinko
  • 3,319
  • 28
  • 31