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

71
Views
Sorting with multiple conditions

I have an array of objects like so:

[
    { 
        required: false,
        sort: 1
    },
    { 
        required: true,
        sort: 2
    },
    { 
        required: false,
        sort: 3
    },
]

I want to sort it by required DESC, sort ASC. How do you do this?

The result I am looking for is:

[
    { 
        required: true,
        sort: 2
    },
    { 
        required: false,
        sort: 1
    },  
    { 
        required: false,
        sort: 3
    },
]

Currently tried with this, which doesnt work. It correctly puts required first, but then ignores sort for the required items:

arr.sort((a, b) => {
    if (a.required) return -1

    return a.sort - b.sort
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can subtract the second required (2) from the first (1) when comparing. If they are the same value, you can logical-OR the left (1) and right (2) sort values.

const data = [
  { required: false , sort: 1 },
  { required: true  , sort: 2 },
  { required: false , sort: 3 },
];

const sorted = data.sort((
  { required: r1, sort: s1 },
  { required: r2, sort: s2 }
) => r2 - r1 || s1 - s2);

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important }

In JavaScript, subtracting booleans results in an integer value that is useful for sorting.

true  - true   //  0 (no change)
true  - false  // +1 (sink to bottom)
false - true   // -1 (float to top)
false - false  //  0 (no change)
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!