How do I sort a hash table in Javascript?

Related searches

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


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?

If you want to iterate through a hash table in JavaScript in order, make an array, populate it with the hash keys, and then sort it.

    var things = new Object ();
    things["hello"] = {"name" : "zzz I fell asleep", "number" : 7};
    things["one"] = {"name" : "something", "number" : 18};
    things["two"] = {"name" : "another thing", "number" : -2};
    var keys = [];
    for (var key in things) {
      if (things.hasOwnProperty(key)) {
    keys.sort ();
    for (i in keys) {
      var key = keys[i];
      var value = things[key];
      document.write (key +"="+value+"\n");

Ordered hash in JavaScript, When initializing the hash table we create an array containing a fixed number of these buckets. var allBuckets = [[], [], [], []] And in order to insert� This means that finding a key in a hashtable is as fast as accessing an array by index. So, while searching, the hash table mechanism gives me O (1) performance for any given key search, since a

My solution

things.sort(function(a,b){return -;});

Algorithms in JavaScript: Hash Tables | by Rohan Paul, Here's an example of how to easily sort a hash by keys: var sorted = Object.keys( hash) .sort(function(a,b) { return +b - +a }) .map(function(k) { return hash[k] });. Hashtables are not sorted. So you need to make a copy of the hash table's key set, sort it, and retrieve the values from the hashtable by iterating through the keys in your sorted list. Or use a sorted hash table substitute, such as TreeMap; that would avoid having to make the copy of the key set.

I developed a function that sorts a hash table by the key, no matter if the value is a number or a string. It keeps the key if the table is an associated table.

function sortHashTableByKey(hash, key_order, remove_key)
    var tmp = [],
        end = [],
        f_order = null;
    remove_key = remove_key || false;
    for (var key in hash)
        if (hash.hasOwnProperty(key))
    if (hash && hash[0] && typeof(hash[0][key_order]) === 'number')
        f_order = function (a, b) { return a - b; };
    function getHash(hash, value)
        for (k in hash)
            if (hash[k] && hash[k][key_order] === value)
                return { key : k, hash : hash[k] };
    for (var i = 0, l = tmp.length; i < l; i++)
        tmp[i] = getHash(hash, tmp[i]);
        if (remove_key)
            delete tmp[i].hash[key_order];
        if (!hash.length)
            end[tmp[i].key] = tmp[i].hash;
    return end;

This will do :

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

things = sortHashTableByKey(things, 'name');

  two: { name: 'another thing', number: -2 },
  one: { name: 'something', number: 18 },
  hello: { name: 'zzz I fell asleep', number: 7 }

Is there a way to sort a map? : javascript, In order to resolve the issue, we can simply store multiple key-value pairs at the same index. So let's amend our hash table: As you might notice,� Click the headers to sort the table. Click "Name" to sort by names, and "Country" to sort by country. The first time you click, the sorting direction is ascending (A to Z). Click again, and the sorting direction will be descending (Z to A):

your parameters are thing1 and thing2, but you're referencing some variables called asp1 and asp2, which, as far as I can tell from the source you've provided, do not exist.

Also, I think what you're looking for is an associative array, which is not instantiated with the [] syntax. See here for more info:

EDIT: I don't think there's an array in Javascript that'll let you do what you want.

You can have plain old array, which will let you do the custom sorting or you can have an associative array, which will let you have the named values.

With the regular array, you can obviously iterate through the indexes.

With the associative array, you can iterate through the names by doing for (var key in myArray)

How to implement a simple hash table in JavaScript, Hash Tables in JavascriptConstructing a Hash Table Implementation for Javascript In JavaScript, all non-scalar objects behave as associative arrays, a mapping In order to access the underlying items, we added the methods ' setItem',� HashTable. prototype. set = function (key, value){this. getBucket (key). set (key, value)} HashTable. prototype. get = function (lookupKey){return this. getBucket (lookupKey). get (lookupKey)} We’ve got a working hash table! Measuring performance. Let’s see how well our hash table is doing.

same as eeerahul, with keys() and String().localeCompare() :

function sort_by_key(t_kv,v_kv){

    ["one", "two", "three"]
    ["one", "three", "two"]    

Hash Tables in Javascript, I am using a hash table in JavaScript, and I want to show the values of the following in a hash table one -[1,10,5] two -[2] three -[3, 30, 300, etc.] I have found the following code.

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. To achieve this, first of all let's be clear about our requirement on following terms

Hash Tables in Javascript Constructing a Hash Table Implementation for Javascript. Javascript is a prototype-based object-oriented language. In JavaScript, all non-scalar objects behave as associative arrays, a mapping from property keys to values. The keys and values can be scalars, objects or functions.

  • You are not having a hastable (aka object) nor a proper array. If you wat to have an object you should initialize it with {} not with []. If you initialize with [] you have an Array, but then do not add to it by means of a["one"] and a["two"] but by a.push(...);. Only after you know what data structure you want, can you bother with sorting. (BTW: foo["bar"] is the same as, use the second, it does not clog the code with string literals and lots of square brackets)
  • Just a note, the order of iteration of the statement can be arbitrary, there is nothing described in the ECMAScript specification about the order of enumeration of the properties, it is implementation dependent... no guarantees, use with care...
  • @CMS: So I should use for (var i = 0; i < keys.length; i++) to be strictly correct?
  • @Kinopiko, exactly, give a look to the following articles for more info: [ 1 ](…) and [ 2 ](…).
  • You can also build your keys array using Object.keys(things). It's also a good practice to store the array length before the for loop's comparison step, so @CMS's for loop from above could be written like for (var i = 0, l = keys.length; i < l; i++). This avoids repeatedly indexing into the keys.length property for a value that doesn't change.
  • OP is using the array things incorrectly so this would not help.
  • @HaykSaakian, how is being the function coming along? as a human being, I really admire anyone's effort to sustain both state and function beyond the mind/body problem. bravo.
  • i should have said "doing this" not "being this" @ToddMorrison
  • Be careful with that syntax. It'll loop over all the properties the object in question has, which includes things other than array keys.
  • ^^ This is true, but shouldn't be an issue as long as it doesn't inherit from anything.