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

269
Vistas
Sorting keys of an object not working as expected- Javascript

I'm sorting the keys in the object:

My object:

data = {AAA: 1, BBB: 2, CCC: 55, VVV: 33, FFF:44}

I'm using the following code to sort:

Object.fromEntries(Object.entries(data).sort(([,v1], [,v2]) => +v2 - +v1))

however it outputs:

{CCC: 55, FFF: 44, VVV: 33, BBB: 2, AAA: 1}

I want to sort the keys in the object which should result:

{AAA: 1, BBB: 2, CCC: 55, FFF: 44, VVV: 33}

and if I try to change the sorting order, still gives results based on the count and not based on the key:

Object.fromEntries(Object.entries(data).sort(([,v1], [,v2]) => +v1 - +v2))

how can I make the above code work for both sorting value and sorting keys of an object?

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

0

That is because you are sorting based on the value of the entries, not the key of the entries. Object.entries() returns a tuple in the following format: [key, value], yet you are only accessing and comparing the values as you are using [, v1] and [, v2]. Change these to [k1] and [k2] respectively (the name doesn't matter, it's the positional argument you're unpacking that matters).

Simply update your accessors to use the first entry in the tuple, which is the key, and use String.prototype.localeCompare:

Object.fromEntries(Object.entries(data).sort(([k1], [k2]) => k1.localeCompare(k2)))

See proof-of-concept below:

const data = {
  AAA: 1,
  BBB: 2,
  CCC: 55,
  VVV: 33,
  FFF: 44
};

console.log(Object.fromEntries(Object.entries(data).sort(([k1], [k2]) => k1.localeCompare(k2))));

about 4 years ago · Juan Pablo Isaza Denunciar

0

const data = {
  AAA: 1,
  BBB: 2,
  CCC: 55,
  VVV: 33,
  FFF: 44
};

console.log(Object.fromEntries(Object.entries(data).sort(([k1], [k2]) => k1.localeCompare(k2))));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Can do it using reduce.

const data = {
  AAA: 1,
  BBB: 2,
  CCC: 55,
  VVV: 33,
  FFF: 44
};
const sorted = Object.keys(data)
  .sort()
  .reduce((obj, key) => {
    obj[key] = data[key];
    return obj;
  }, {});
console.log(sorted);

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