Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
How to conditionally sort and right shift a JSON array?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!