Javascript Ordering Object: Order Your Hash

In my last post I discussed creating a method to inject values into a javascript object in a specific order. However, it was brought to my attention that natively, the javascript standard (ECMA) never specifically says this is a supported feature, and that some browsers treat this differently. So knowing that and the fact that I needed this functionality I created my own object capable of handling such! Introducing my Ordering object.

The theory here is that you can create a new object by passing in a normal javascript object. Also either in the constructor you can specify a sorting function or manually call sort against your object. From then on when you insert into your object it will be placed in accordance to your sort routine. The beauty of this is that it brings together the power of the javascript Object and the javascript Array. Here is how to create a new object:

// Our sort function, this is how we want to keep our object ordered
var sf = function(ak,av,bk,bv){
    var v1 = av.toLowerCase(),v2 = bv.toLowerCase();

    if(v1 < v2) return -1;
    if(v1 > v2) return 1;
    return 0;

var ord = new Ordering({ 
    Tom: 'first', 
    Jane: 'second', 
    Sally: 'third', 
    Bill: 'forth', 
    Lee: 'fifth', 
    Carl: 'sixth', 
    Stan: 'seventh', 
    Earl: 'eighth', 
    Paul: 'ninth', 
    Tray: 'tenth' 
}, sf);

This creates an ordering object which will be sorted alphabetically by the values. Keep in mind the values can be any data type you wish, and you can handle them how you need to in your sort functions. But wait! There's More!

If you need to inject an item at a specific position, you can use the inject method:

ord.inject('Trent', 'NEW ITEM', function(pk, pv, nk, nv){ 
    return (nk=='Earl'); 

To set a value:


To erase a value:


To loop over the object (in order):

str = '';
    str += k +': '+ v +'\n';

To resort your object (pass in an optional sort function like the one from the constructor)


There are also other functions implemented like:

  • feed(object) (populate the object)
  • every(fn)
  • some(fn)
  • map(fn)
  • filter(fn)
  • subset(fn)
  • slice(start, end)
  • get(key)
  • getAt(numeric_index)
  • indexOf(key)
  • clone()
  • keys() (return an array of the keys, in order)

The source is also very straight forward, so don't be shy if you're unaware how to use something, just dive right in and figure it out. There is also an html file with the source with some examples. Enjoy!