etayluz
etayluz

Reputation: 16416

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?

Upvotes: 1

Views: 1746

Answers (6)

Walter Laurent
Walter Laurent

Reputation: 9

var items = { "key" : [
  "key_1=z",
  "key_2=a",
  "key_3=b",
  "key_4=y"
            ]};


function proto (thisone, order) {
proto[order] = thisone;

}
function proto2(thisone) {
proto2[thisone.split("=")[0]] = thisone.split("=")[1];

}
 function trierMax (value, order2) {
 
 if (!proto2[value.split("=")[0]]) {
 proto(value, order2);
} else {
    proto("null=zzzzz", order2);
}
for (var y = 0; y < sp.length; y++) {

if (sp[y].split("=")[1] < proto[order2].split("=")[1] && !proto2[sp[y].split("=")[0]]) {
proto(sp[y], order2);
}
}
}
var sp = items.key;

for (var i = 0; i < sp.length; i++) {

trierMax(sp[i], i);
proto2(proto[i]);
}

for (var p = 0; p < sp.length; p++) {
items.key[p] = proto[p];
}

console.log(items);

without "sort"

Upvotes: 0

Danielo515
Danielo515

Reputation: 7071

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

Upvotes: 1

Mr.Developer
Mr.Developer

Reputation: 545

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);

Upvotes: 2

Himanshu Singh
Himanshu Singh

Reputation: 1953

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

let sorted = {};

Object.entries(dict) //enteries gives the arrray [key, value] for each entry
  .sort((a,b) => { 
    //console.log(a,b);
    //if value is equal, compare with key
    if(a[1] == b[1])  return a[0]<b[0] ? -1 : 1;
    //else compare value
    return a[1]<b[1] ? -1 : 1;
  })
  .forEach((ele) => {
    //console.log(ele);
    //reassign to a new object
    sorted[ele[0]] = ele[1] 
   });
  
console.log(sorted);

Upvotes: 0

samnoon
samnoon

Reputation: 1743

You can use String.prototype.localCompare() as here:

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

var items = Object.keys(dict).map(function(key) {
  return [key, dict[key]];
});
items.sort((first, second) => first[1].localeCompare(second[1]));
console.log(items);

Upvotes: 0

Haywirehax
Haywirehax

Reputation: 13

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?

Upvotes: 0

Related Questions