Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda