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

258
Vistas
Sort a dictionary alphabetically by value in JavaScript

Here is my dictionary:

const dict = {
  "key_1" : "z",
  "key_2" : "a",
  "key_3" : "b",
  "key_4" : "y"
};

I want to sort it alphabetically by value so it looks like this:

const sorted_dict = {
  "key_2" : "a",
  "key_3" : "b",
  "key_4" : "y",
  "key_1" : "z"
};

This is what I think should work:

var items = Object.keys(dict).map(function(key) {
        return [key, dict[key]];
    });

items.sort((a, b) => a[1] - b[1]);
console.log(items)

But it's not sorting at all:

[
    [
        "key_1",
        "z"
    ],
    [
        "key_2",
        "a"
    ],
    [
        "key_3",
        "b"
    ],
    [
        "key_4",
        "y"
    ]
]

Why is the sorting not working?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Hope this code will help you

const dict = {
  key_1: "z",
  key_2: "a",
  key_3: "b",
  key_4: "y",
};

const sortable = Object.fromEntries(
  Object.entries(dict).sort(([, a], [, b]) => a.localeCompare(b))
);

console.log(sortable);

about 4 years ago · Santiago Trujillo Denunciar

0

There is no such thing as a sorted dictionary in JavaScript. There is no guarantee that insertion order nor alphabetical order will be preserved, even if you sometimes get the illusion that it is, you should never rely on it. If you need order you must use an array, a set or a Map

about 4 years ago · Santiago Trujillo Denunciar

0

The following code will sort the dictionary by the charcode, meaning the order of the alphabet:

const dict = {
  "key_1" : "z",
  "key_2" : "a",
  "key_3" : "b",
  "key_4" : "y"
};

const sorted = Object.entries(dict)
  .sort(([, v1], [, v2]) => v1.toUpperCase().charCodeAt(0) - v2.toUpperCase().charCodeAt(0))
  .reduce((obj, [k, v]) => ({
    ...obj,
    [k]: v
  }), {})

console.log(sorted)
//{key_2: 'a', key_3: 'b', key_4: 'y', key_1: 'z'}

However, this will only work when the value is one character. Do you which for a function that also sorts bigger values?

about 4 years ago · Santiago Trujillo 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