Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a hash table in Javascript?

Tags:

People also ask

Can you sort a hash table?

Before moving forward, we need to understand that it is not possible to sort a Hashtable since the data is stored by the hashcode of the key, not by the index . So to sort the data of a Hashtable, we need to have a sortable object like an array or an ArrayList. Sorting has to be done on Key or Value.

Is there a hash table in JavaScript?

In JavaScript, a “hash table” is a data structure that can be utilized to map keys to their specified values. It is also known as a “hash map“. Hash tables efficiently perform the insertion and deletion operation for a key-value pair and search the value of a key within a hash table.


I have a Javascript hash table, like so:

var things = [ ];
things["hello"] = {"name" : "zzz I fell asleep", "number" : 7};
things["one"] = {"name" : "something", "number" : 18};
things["two"] = {"name" : "another thing", "number" : -2};

I want to sort these into order by name, so if I iterate through the hash table it will go in order

another thing
something
zzz I fell asleep

I tried doing this:

function compareThings(thing1, thing2) {
    var name1 = thing1["name"].toLowerCase();
    var name2 = thing2["name"].toLowerCase();
    if (name1 < name2) {
        return -1;
        }
    if (name1 > name2) {
        return 1;
        }
    return 0;
}

things.sort(compareThings);

But it doesn't seem to work.

Edit: it occurs to me that perhaps a sorted hash table is an oxymoron. If so, what's the best way to get access to a sorted list of the things here?