how do I sort a dictionary by key like
dict["word_21"] = "Hello Java";
dict["word_22"] = "Hello World";
dict["word_11"] = "Hello Javascript";
so that I get
dict["word_22"] = "Hello World";
dict["word_21"] = "Hello Java";
dict["word_11"] = "Hello Javascript";
There are word_number combinations on indices only and the values are strings. The indices are distinct (no equal values) but could be "undefined" in an error case
Edit: Actually I need the descending and ascending order of it. But the descending order is what I need at the moment.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
Sort Dictionary Using a for Loop We can sort a dictionary with the help of a for loop. First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary.
To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.
A javascript object, here used as a key-value-map (called "dictionary"), has no order; ie. you can't sort it.
You would need an array for that, e.g.
[
{id: "word_11", entry:"Hello Javascript"},
{id: "word_21", entry:"Hello Java"},
{id: "word_22", entry:"Hello World"},
]
then you could sort that by id or by entry. You might use your id-sort-algorithm for that.
Or you could use an array of your keys to sort, next to the unsorted data structure. This might be the best (efficient) and simplest approach:
var dict = {
"word_21": "Hello Java",
"word_22": "Hello World",
"word_11": "Hello Javascript"
}; // init (like your example)
var keys = Object.keys(dict); // or loop over the object to get the array
// keys will be in any order
keys.sort(); // maybe use custom sort, to change direction use .reverse()
// keys now will be in wanted order
for (var i=0; i<keys.length; i++) { // now lets iterate in sort order
var key = keys[i];
var value = dict[key];
/* do something with key & value here */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With