How do I sort a hash table in javascript?

Posted by Colen on Stack Overflow See other posts from Stack Overflow or by Colen
Published on 2010-05-08T03:35:46Z Indexed on 2010/05/08 3:48 UTC
Read the original article Hit count: 445

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about sort