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

136
Vistas
Sort array of objects by their numerical keys

I'm trying to sort an array, where its objects consist of a dynamic key of type number.

Now I want to sort the objects so that the numbers start from the smallest first -- the number I mean is the key of the object.

Here's my code

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

arr.sort((a,b) => {
  if (a < b) {
    return -1;
  }

  if (a > b) {
    return 1;
  }

  return 0;
});

console.log(arr);

The order of the objects should be:

[{"1": 42},{"3":32},{"5":48}]
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You'll need to extract the keys... like with Object.keys:

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

arr.sort((a,b) => Object.keys(a)[0] - Object.keys(b)[0]);

console.log(arr);

about 4 years ago · Juan Pablo Isaza Denunciar

0

use this and it should work

let arr = [{"3": 32}, {"1": 42}, {"5": 48}];

let getKey=(array)=> Object.keys(array)[0]

arr.sort((a,b) => (getKey(a) - getKey(b)))

console.log(arr)
about 4 years ago · Juan Pablo Isaza Denunciar

0

This should work

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

arr.sort((a,b) => {
  const firstKey = Object.keys(a)[0]
  const secondKey = Object.keys(b)[0]
    return  secondKey - firstKey
})
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