Search code examples
javascriptsortinghashtable

How do I sort a hash table in Javascript?


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?


Solution

  • 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.

    <html>
    <body>
    <pre>
      <script>
        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.push(key);
          }
        }
        keys.sort ();
        for (i in keys) {
          var key = keys[i];
          var value = things[key];
          document.write (key +"="+value+"\n");
        }
      </script>
    </pre>
    </body>
    </html>