Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently

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.

like image 675
user1054134 Avatar asked Jun 08 '12 10:06

user1054134


People also ask

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

How do you sort a dictionary with respect to 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.

Can I sort the object keys JavaScript?

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.


1 Answers

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 */
} 
like image 95
Bergi Avatar answered Nov 09 '22 22:11

Bergi