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

115
Vistas
Array of object not sorting on a key

I have the following array of objects that I want to order by name key. For some reason if I try to sort by the "name" key it doesn't sort. If I sort by a "price_value" key it works .

let arr = [
  {
    "name": "Road Bike",
    "slug": "road-bike",
    "price_value": 2499
  },
  {
    "name": "Laptop",
    "slug": "laptop",
    "price_value": 1299,
  },

];

let br = [...arr].sort((a, b) => a.name - b.name)[0].name;

console.log(br) //should be Laptop, even if you try to sort on slug key doesn't work

I always get Road Bike as first element. If I try to sort on price_value key it works normally.

let br = [...arr].sort( (a,b) => a.price_value - b.price_value )[0].name;
console.log( br ) //It's Laptop as expected

Where is the problem?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You cannot subtract string. a.name - b.name is not a valid operation and returns NaN.

It should work if you do:

let br = [...arr].sort((a, b) => a.name.localeCompare(b.name))[0].name;
about 4 years ago · Juan Pablo Isaza 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