Sorting keys alphanumerically

I have a large dictionary and I would like to extract the keys from this sorted alphanumerically.  Does anybody have a method for doing this?

Essentially I am reading data from a json file and would like to use the keys as a list to the user to select from.

This is where I am at present:

using Toybox.WatchUi as Ui;

var machines = null;

...

    //! Load your resources here
    function onLayout(dc) {
        machines = Ui.loadResource(Rez.JsonData.jsonFile);
        var mList = machines.keys();
        System.println("onLayout: array of machines: "+mList);
    }

  • You have to do the sort yourself.

    Check everything in the dictonary and add it in the right place in something like an array of strings.

    Start with something like:

    for(var i=0;i<mList.size();i++) {

      myArray=doSort(myArray,mList[i];

    }

    where doSort() add the value from mList[i] at the proper place in the array

  • Thanks Jim, that was what I suspected.  You wouldn't happen to know if the order of the keys is guaranteed to be the same each time, or are they pretty much a random order.  I would guess the keys are a hash and are returned in the hash order.

    BTW with the documentation as separate html pages I am finding it difficult to search for the information I am after, though I guess I could grep through the pages on the file-system.

  • I think it's hash order.  There's a bunch of things in the Programmer's Guild which might make it seasier to find your way in the API documentation.

    One thing to note is that

    if(str1>str2) {}

    won't do what you want,  That's why there's things like

    str1.equals(str2)

    If you are comparing strings, you probably want to use toUpper() or toLower() on the strings so you can ignore case, and I'm thinking maybe toCharArray() to do char by char compares.

  • Just an update in case anyone else needs to do this.  I played around with sort algorithms from the Numerical Recipes book/website, but in the end I simply added an order field to the dictionary items in the file and did a single loop sort using that field - simple.  However this does make it a manual sort which gets stuck a bit in my craw.

  • Well, if you're not 100% happy with that solution:
    - You could an array to the data with the keys in sorted order, so there's no need to sort within the CIQ app
    - You could use custom build step in Eclipse to run a script (Python, bash or something) that would automatically sort the keys for you, so there's no need for any manual sorting of data (unless you already do that when you generate the data -- I'm not sure if you're adding the order field manually or not.)