如何在 Javascript 中对哈希表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2792850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:56:43  来源:igfitidea点击:

How do I sort a hash table in Javascript?

javascriptsortinghashtable

提问by Colen

I have a Javascript hash table, like so:

我有一个 Javascript 哈希表,如下所示:

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?

编辑:在我看来,排序的哈希表可能是矛盾的。如果是这样,访问此处排序的事物列表的最佳方法是什么?

回答by

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.

如果您想在 JavaScript 中按顺序遍历哈希表,请创建一个数组,使用哈希键填充它,然后对其进行排序。

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

回答by mathieu

My solution

我的解决方案

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

回答by Atinux

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 }
]
*/

回答by Daniel Schaffer

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

您的参数是thing1and thing2,但您引用了一些名为asp1and 的变量asp2,据我从您提供的来源中得知,这些变量不存在。

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

另外,我认为您正在寻找的是一个关联数组,它没有用[]语法实例化。请参阅此处了解更多信息:

http://www.quirksmode.org/js/associative.html

http://www.quirksmode.org/js/associative.html

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

编辑:我不认为 Javascript 中有一个数组可以让你做你想做的事。

You can have plain old array, which will let you do the custom sorting oryou 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)

使用关联数组,您可以通过执行以下操作来遍历名称 for (var key in myArray)

回答by Guy Kastenbaum

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

与 eeerahul 相同,带有 keys() 和 String().localeCompare() :

function sort_by_key(t_kv,v_kv){
  return(Object.keys(t_kv).sort(
    function(a,b){return(
      String(t_kv[a][v_kv]).localeCompare(String(t_kv[b][v_kv])))}))
}

t={two:{s:'two',n:2},three:{s:'three',n:3},one:{s:'one',n:1}}
sort_by_key(t,'n')
    ["one", "two", "three"]
sort_by_key(t,'s')
    ["one", "three", "two"]