2

I have a dictionary with some key:value pairs like the following.

rank = {
            "Team 1" : 34,
            "Team 2" : 55,
            "Team 3" : 29,
            "Team 4" : 61,
            ...
        }

Keys are team names and values are points at the end of the season, so I want to sort couples based on their values in order to print a final ranking.

Can someone help me? Thanks in advance

Gio Bact
  • 541
  • 1
  • 7
  • 23
  • 1
    convert this to array, then sort – k102 Jul 04 '16 at 14:59
  • You may find your response here: http://stackoverflow.com/questions/25500316/sort-a-dictionary-by-value-in-javascript – L01c Jul 04 '16 at 15:01
  • 1
    Hence it's usually easier to use `var rank = [{'name':'Team 1', 'value':34}, {'name':'Team 2', 'value':55}, ...];` Then you can use all the array goodness to sort/filter/map your data. – Shilly Jul 04 '16 at 15:11

1 Answers1

5

Object keys and values in Javascript have no intrinsic order. Before you can sort them into a desired order, you need to store them in an ordered structure.

Let's get the items into an Array, which does have intrinsic order:

var object = {
  a: 1,
  b: 5,
  c: 2
}

var keyValues = []

for (var key in object) {
  keyValues.push([ key, object[key] ])
}

The keyValues array now holds ['a', 1], ['b', 5], ['c', 2]. Let's sort this array, using the second value in each pair for comparison:

keyValues.sort(function compare(kv1, kv2) {
  // This comparison function has 3 return cases:
  // - Negative number: kv1 should be placed BEFORE kv2
  // - Positive number: kv1 should be placed AFTER kv2
  // - Zero: they are equal, any order is ok between these 2 items
  return kv1[1] - kv2[1]
})

Now keyValues is sorted from lesser to greater. Note that you can't convert it back to an object, or the order will be lost.

salezica
  • 74,081
  • 25
  • 105
  • 166