Javascript Sort Dict


Date: 2021-09-21
Language: JavaScript
Code Link: Github

Background

Needed to sort dicts to create the right order to list items on a website

Problem

Need to sort a dict by the initial key using JavaScript
DictExample = {
            "a": {
                "key1": "value1"
            },
            "b": {
                "key2": "value2"
            },
            "c": {
                "key3": "value3"
            },
          }

Solution

Seems to work. You can remove reverse depending on your order requirements.
Answer
function sortOnKeys(dict) {
    var sorted = [];
    for (var key in dict) {
      sorted[sorted.length] = key;
    }
    sorted.sort().reverse();

    var tempDict = {};
    for (var i = 0; i < sorted.length; i++) {
      tempDict[sorted[i]] = dict[sorted[i]];
    }

    return tempDict;
  }
const DictExampleOrdered = sortOnKeys(DictExample);