Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda