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

后端 未结 5 939
暗喜
暗喜 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:57

    Simply put, the dictionary type does not have a keys() method, while the Object type does. You can pass the Object.keys() method an iterable and get the keys back as a list which has a .sort() method.

    Object.keys({r:2,d:2,c:3,p:0})
    // returns ["r", "d", "c", "p"]
    Object.keys({r:2,d:2,c:3,p:0}).sort()
    // returns ["c", "d", "p", "r"]
    Object.keys([6,7,8,9])
    // returns ["0", "1", "2", "3"]
    

    And finally, let's jsFiddle the OP's code.

    Update: Bergi's answer had too much going on and I totally missed the "good answer" part. I didn't even notice he did the same thing I did in my jsFiddle.

提交回复
热议问题