Friday, 18 January 2019

Sorting a dictionary in javascript

Once time, a user of stackoverflow is asking how to sort a dictionary in javascript. Here I would like to share a simple implementation which will return an array whose each item is an item in the input dictionary and sorted according to sort function. And test code also included.

javascript
var sortDict = function (dict, compare) {
  let keys = Object.keys(dict)
  let sortedKeys = keys.sort(compare)
  result = []
  for (let i in sortedKeys) {
    let aKey = sortedKeys[i]
    let anItem = {}
    anItem[aKey] = dict[aKey]
    result.push(anItem)
  }
  return result
}
var a = {"zabc": 8, "abc": 6, "jabc": 3, 'baaa': '5'}
console.log(JSON.stringify(sortDict(a, function (k1, k2) {
  // return a[k1] > a[k2]
  return k1 > k2
})))

You will see the sorted result printed.


To have different sorting criteria, just have your own compare function implementation. Thank you!

No comments: