Sort a dictionary by value in JavaScript

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

    First things first, what you may call a 'dictionary' is called an 'Object' in JavaScript. Your 'dict' variable is an object.

    Objects are not ordered in JS, so you cannot sort an object. Fortunately arrays are ordered; we will convert your dictionary to an array. Just take a look below.

    //dict -> a js object
    var dict = {"x" : 1,
            "y" : 6,
            "z" : 9,
            "a" : 5,
            "b" : 7,
            "c" : 11,
            "d" : 17,
            "t" : 3};
    
    //Use the 'keys' function from the Object class to get the keys of your dictionary
    //'keys' will be an array containing ["x", "y", "z"...]
    var keys = Object.keys(dict);
    
    //Get the number of keys - easy using the array 'length' property
    var i, len = keys.length; 
    
    //Sort the keys. We can use the sort() method because 'keys' is an array
    keys.sort(); 
    
    //This array will hold your key/value pairs in an ordered way
    //it will be an array of objects
    var sortedDict = [];
    
    //Now let's go throught your keys in the sorted order
    for (i = 0; i < len; i++)
    {
        //get the current key
        k = keys[i];
    
        //show you the key and the value (retrieved by accessing dict with current key)
        alert(k + ':' + dict[k]);
    
        //Using the array 'push' method, we add an object at the end of the result array
        //It will hold the key/value pair
        sortedDict.push({'key': k, 'value':dict[k]});
    }
    
    //Result
    console.log(sortedDict);
    

    You can try it here

    If you want to change the sorting, have a look here

    If you want the first five biggest values, well, loop over sortedDict with a for loop 5 times and get those values out:

    function getFiveFirstValues(){
        var valuesArray = [];
        for (i = 0; i < 5; i++)
        {
            valuesArray.push(sortedDict[i].value);
        }
        return valuesArray;
    }
    

    Please remember that in JavaScript, objects are UNORDERED. They may seem to be ordered, but they are not, and depending on the JS implementation of your browser their order can be different.

    In this example, sortedDict is an Array (which is ordered) and thus can be sorted. In each element of that array, you will find a KEY and VALUE pair for each pair of your 'dictionary'.

    0 讨论(0)
  • 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)
    })
    
    0 讨论(0)
  • 2020-12-03 17:20

    It may not be straight forward in JavaScript.

    var dict = {
      "x": 1,
      "y": 6,
      "z": 9,
      "a": 5,
      "b": 7,
      "c": 11,
      "d": 17,
      "t": 3
    };
    
    // Create items array
    var items = Object.keys(dict).map(function(key) {
      return [key, dict[key]];
    });
    
    // Sort the array based on the second element
    items.sort(function(first, second) {
      return second[1] - first[1];
    });
    
    // Create a new array with only the first 5 items
    console.log(items.slice(0, 5));

    The first step, creating items array, is similar to Python's

    items = map(lambda x: [x, var[x]], var.keys())
    

    which can be conveniently written as

    items = list(dict.items())
    

    and the sorting step is similar to Python's sorting with cmp parameter

    items.sort(cmp=lambda x, y: y[1] - x[1])
    

    and the last step is similar to the Python's slicing operation.

    print items[:5]
    // [['d', 17], ['c', 11], ['z', 9], ['b', 7], ['y', 6]]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 17:26

    You can try the following code. It gets sorted integer array by value.

    jsFiddle link

     function sortJsObject() {
        var dict = {"x" : 1, "y" : 6,  "z" : 9, "a" : 5, "b" : 7, "c" : 11, "d" : 17, "t" : 3};
    
        var keys = [];
        for(var key in dict) { 
           keys[keys.length] = key;
         }
    
         var values = [];     
         for(var i = 0; i < keys.length; i++) {
             values[values.length] = dict[keys [i]];
         }
    
         var sortedValues = values.sort(sortNumber);
         console.log(sortedValues);
    }
    
    // this is needed to sort values as integers
    function sortNumber(a,b) {
       return a - b;
    }
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题