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

147
Views
I am trying to order the array by most valued, from lowest to highest, but those with 0 value are ordered after the highest valued,

I am trying to order the array by most valued, from lowest to highest, but those with 0 rating are ordered after the highest valued, and then from highest to lowest by price

const product = [
  {mostValued:5, price: 5},
  {mostValued:0, price: 14},
  {mostValued:0, price: 58},
  {mostValued:3, price: 33},
  {mostValued:0, price: 25},
  {mostValued:4, price: 47},
]
 // code
product.sort((a, b) =>
      a.mostValued == b.mostValued 
        ? b.price - a.price
        : a.mostValued - b.mostValued
);

Those with 0 stars should be sorted after, highest to lowest by price, so the expected output would be

[
  {mostValued:3, price: 33},
  {mostValued:4, price: 47},
  {mostValued:5, price: 5},
  {mostValued:0, price: 58},
  {mostValued:0, price: 25},
  {mostValued:0, price: 14}
];
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Easiest way would be to coalesce 0s (and other falsy values?) to Infinity:

product.sort((a, b) =>
    (a.mostValued || Infinity) - (b.mostValued || Infinity) ||
    b.price - a.price
);

Alternatively, specifically give those with mostValued == 0 a priority:

product.sort((a, b) =>
    (a.mostValued == 0) - (b.mostValued == 0) ||
    a.mostValued - b.mostValued ||
    b.price - a.price
);
about 4 years ago · Santiago Gelvez 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!