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

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

    If you just want to sort keys in an object, the following is fine (its a one liner)

    /**
     * (typescript) returns the given object with keys sorted alphanumerically.
     * @param {T} obj the object to sort
     * @returns {T} the sorted object
     */
     const sort = (obj: T): T => Object.keys(obj).sort()
            .reduce((acc, c) => { acc[c] = obj[c]; return acc }, {}) as T
    

    or the same in javascript

    /**
     * (javascript) returns the given object with keys sorted alphanumerically.
     * @param {T} obj the object to sort
     * @returns {T} the sorted object
     */
     const sort = (obj) => Object.keys(obj).sort()
            .reduce((acc, c) => { acc[c] = obj[c]; return acc }, {})
    

提交回复
热议问题