Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!