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

212
Views
Array.sort() on multiple properties

I have an array, productData with multiple properties. This is how I currently sort the array by monthlyCost, ascending.
How can I modify this to sort all items by a boolean property isPromoted, followed by monthlyCost?
My array should start with all items where isPromoted == true sorted by monthlyCost, then all items where isPromoted == false sorted by monthlyCost.

    productData.sort((a, b) => {
      if (a.monthlyCost > b.monthlyCost) {
        return 1;
      } else if (a.monthlyCost < b.monthlyCost) {
        return -1;
      } else {
        return 0;
      }
    });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use this callback:

productData.sort((a, b) => +b.isPromoted - +a.isPromoted || a.monthlyCost - b.monthlyCost);

The unary plus is optional in plain JavaScript, but in a TypeScript context, you'll need to be explicit about the conversion to number and apply +.

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!