Sunday, August 30, 2009

Sorting in a Firefox extension

If you're developing a Firefox extension, and you use Javascript's Array.sort to sort an associative array, you might not like the results.  As far as I can tell, it does nothing.  I built an array keyed on a field called loc, which wasn't to be used in sorting, and another field seq, which was to be used.  Multiple rows could have the same loc, so the associative array was handy in allowing me to easily make sure only the latest seq for each loc was recorded.  Alas, it was not to be.

However, you can get around this by giving your array numeric indexes.  I needed to ensure that each loc only used one index and if it was already in sorted, I should overwrite that array element.  Here's the bit of code I used to make a sortable array:

    var sorted = new Array();
    var locKeys = new Array();
   
    for( var r in rows )
    {
        var ad = rows[r];

        instance.seq = getSeq(ad);
        instance.loc = getLoc(ad);
        if( !(
instance.loc in locKeys) )
        {
            locKeys[
instance.loc] = sorted.length;
        }
        sorted[locKeys[
instance.loc]] = instance;
    }

Now sorted will actually re-arrange itself when I call sorted.sort().

No comments: