Sort a dictionary by value in JavaScript

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

提交回复
热议问题