Is there a way to sort the keys in a dict? Preferably with Javascript

terenceformer's icon

Right now I'm just being careful with how I add entries so that they're in a preferred order, but it would be nice to have a sort() method. I can imagine how I can create a function that does this, but it'd be a PITA. Thanks for any help :)

Nikolas K's icon

Hi Terenceformer,

Couldn't you get the keys of the dict in an array, sort that with myArray.sort() and work with that?
Just be careful when getting the keys, as if the dict has a single key, the myDict.getkeys() will return a string with the name of the key instead of an array.

-N

terenceformer's icon

I should have specified that I wanted them sorted in the dictionary. So your right, I would begin writing a sort function with your strategy, then re-adds all the items based on that array... But nuts to that. I realized that it will be easier to just sort the array every time I request the keys rather than having them stored sorted (those words look weird next to each other eh).
Thanks the reply, and for warning us of that annoying issue with single key dictionaries ;)

terenceformer's icon

For those working with dict in JS, these might be handy:

// turn an array of strings describing a dict hierarchy path into a key
function makePath(arr)
{
    if (arr.length==0){ return []; }
    var path = arr[0];
    for (i=1; i
    { path = path + "::" + arr[i]; }
    return path;
}
// make a key out of an array (up to an index) and get its values as a sorted array
function getItems(arr, idx)
{
    var vals = [];
    var key = makePath(arr.slice(0, idx));
    if (idx == 0)
    { vals = d.getkeys(); }
    else if (d.gettype(key) == "dictionary")
    { vals = d.get(key).getkeys(); }
    else
    { vals = d.get(key); }    

    if ( typeof vals == "string"){ vals = [vals]; }
    else { vals.sort(); }

    return vals;
}