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

184
Vistas
sort a javascript object by key : '10' is before '05'

I'm using the following function to sort an object by keys.

The problem is when I have to sort '05' and '10', the '10' is sorted before the '05'

function sortObj(obj) {
  return Object.keys(obj).sort().reduce(function(result, key) {
    result[key] = obj[key];
    return result;
  }, {});
}

let list = {
  '10': "Ann",
  '05': 75
};
let arr = sortObj(list);
console.log(arr);

Object { "10": 75, "05": "Ann" }

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

0

Javascript objects are not ordered by insertion order. To demonstrate, change .sort() to .reverse()

Does JavaScript guarantee object property order?

Seems like you can use a map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared

about 4 years ago · Juan Pablo Isaza Denunciar

0

Ordering an object makes little sense, because objects don't concern itself about the order it is as you access it's values by a key.

Though you can store your data in a Map which has a key-value structure that honors it's order of insertion.

function sortObj(obj) {
  return new Map(
    Object.entries(obj).sort(([a], [b]) => {
      return a - b;
    })
  );
}

let list = {
  '11': 'Beth',
  '10': "Ann",
  '05': 75,
  '07': true
};

let map = sortObj(list);
for (const [key, value] of map) {
  console.log(key, value);
}

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