sorting - Sort dictionary of key:value pairs in javascript -


this question has answer here:

i have dictionary key:value pairs following.

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

keys team names , values points @ end of season, want sort couples based on values in order print final ranking.

can me? in advance

object keys , values in javascript have no intrinsic order. before can sort them desired order, need store them in ordered structure.

let's items array, have intrinsic order:

var object = {   a: 1,   b: 5,   c: 2 }  var keyvalues = []  (var key in object) {   keyvalues.push([ key, object[key] ]) } 

the keyvalues array holds ['a', 1], ['b', 5], ['c', 2]. let's sort array, using second value in each pair comparison:

keyvalues.sort(function compare(kv1, kv2) {   // comparison function has 3 return cases:   // - negative number: kv1 should placed before kv2   // - positive number: kv1 should placed after kv2   // - zero: equal, order ok between these 2 items   return kv1[1] - kv2[1] }) 

now keyvalues sorted lesser greater. note can't convert object, or order lost.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -