Sort a dictionary by value in JavaScript

前端 未结 5 1387
北海茫月
北海茫月 2020-12-03 16:40

Here is my dictionary:

const dict = {
  \"x\" : 1,
  \"y\" : 6,
  \"z\" : 9,
  \"a\" : 5,
  \"b\" : 7,
  \"c\" : 11,
  \"d\" : 17,
  \"t\" : 3
};
         


        
5条回答
  •  情歌与酒
    2020-12-03 17:24

    Strictly speaking, you cannot sort a "dictionary" (JavaScript object), because JavaScript objects have no order. They are merely a "bag" of key/value pairs.

    If you want to find the n largest values in the object, then one way or another you need to convert the object into an array, whose elements are ordered, such as with @thefourtheye's solution. If you want to sort the keys, then well, sort them with Object.keys(object).sort() as another answer shows you how to.

提交回复
热议问题