sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently

后端 未结 5 933
暗喜
暗喜 2020-12-11 14:54

how do I sort a dictionary by key like

dict[\"word_21\"] = \"Hello Java\";
dict[\"word_22\"] = \"Hello World\";
dict[\"word_11\"] = \"Hello Javascript\";
         


        
5条回答
  •  温柔的废话
    2020-12-11 15:33

    Try this

    var sorted = [];
    for(var key in dict) {
        sorted[sorted.length] = key;
    }
    sorted.sort();
    

    Sorting dict on its keys and writing it back to the object does not make sense to me, but here it goes:

    function sortOnKeys(dict) {
    
        var sorted = [];
        for(var key in dict) {
            sorted[sorted.length] = key;
        }
        sorted.sort();
    
        var tempDict = {};
        for(var i = 0; i < sorted.length; i++) {
            tempDict[sorted[i]] = dict[sorted[i]];
        }
    
        return tempDict;
    }
    
    dict = sortOnKeys(dict);
    

提交回复
热议问题