search

Home  >  Q&A  >  body text

node.js - node 字典序排序

如何用node做字典序排序,比如b=1,a=2,c=3, 排完后是a=2,b=1,c=3,

迷茫迷茫2867 days ago933

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 11:34:54

    Copied from @xelz, but avoiding some of the pitfalls of old JavaScript:

    jslet dict = {a: 3, b:1, c:2};
    for (let key of Object.keys(dict).sort()) {
      console.log(key, dict[key]);
    }
    

    Tested and passed in Firefox 28.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:34:54

    The dictionary is unordered, but there is a default order for traversing the dictionary.

    If the subject wants to change the default order of traversing the dictionary, just

    function sortDict(dict) {
        var dict2 = {}, 
            keys = Object.keys(dict).sort();
    
        for (var i = 0, n = keys.length, key; i < n; ++i) {
            key = keys[i];
            dict2[key] = dict[key];
        }
    
        return dict2;
    }
    

    However, this method seems to be invalid for numeric keys. When you need numeric keys, add a prefix (in fact, it is not a real dictionary without a prefix)


    Downstairs, please don’t use in when traversing the array. This kind of error is difficult to find. . .

    function sortEach(dict, fn) {
        var keys = Object.keys(dict).sort();
    
        for (var i = 0, n = keys.length, key; i < n; ++i) {
            key = keys[i];
            fn(dict[key], key, dict);
        }
    }
    

    Thank you Evian, you can still do it:

    javascriptfor (var key of Object.keys(dict).sort()) {
        // do something with dict[key]
    }
    
    

    reply
    0
  • 阿神

    阿神2017-04-17 11:34:54

    Sorting a dictionary is a false proposition, because the dictionary is 无序 and you cannot change its order

    If you want to 有序遍历 it, use

    for (var key in Object.keys(dict).sort()) {
        // do something with dict[key]
    }
    

    reply
    0
  • Cancelreply