How do I sort a hash table in Javascript?
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))
{
tmp.push(hash[key][key_order]);
}
}
if (hash && hash[0] && typeof(hash[0][key_order]) === 'number')
{
f_order = function (a, b) { return a - b; };
}
tmp.sort(f_order);
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;
}
else
{
end.push(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 }
]
*/
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>
My solution
things.sort(function(a,b){return a.name - b.name;});