Sort a dictionary by value in JavaScript

前端 未结 5 1402
北海茫月
北海茫月 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:09

    The answer provided by @thefourtheye works to an extent, but it does not return the same "dictionary" structure.

    If you want to return a sorted object with the same structure you started with, you can run this on the items returned from the accepted answer:

    sorted_obj={}
    $.each(items, function(k, v) {
        use_key = v[0]
        use_value = v[1]
        sorted_obj[use_key] = use_value
    })
    

    Combine them for a single function that sorts a JavaScript object:

    function sort_object(obj) {
        items = Object.keys(obj).map(function(key) {
            return [key, obj[key]];
        });
        items.sort(function(first, second) {
            return second[1] - first[1];
        });
        sorted_obj={}
        $.each(items, function(k, v) {
            use_key = v[0]
            use_value = v[1]
            sorted_obj[use_key] = use_value
        })
        return(sorted_obj)
    } 
    

    Example:

    Simply pass your object into the sort_object function:

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

    Result:

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

    "Proof":

    res = sort_object(dict)
    
    $.each(res, function(elem, index) {
        alert(elem)
    })
    

提交回复
热议问题