Question: I'm trying to get rid of some of the horrible nested loops in the following code. 
Essentially is moving TDs to top rows based on whether the current row has the current cell. You can see the execution here:
<http://jsfiddle.net/Jq8sk/>

How can I clean it up and avoid this level of depth. Any help is appreciated.

```
var trs = $('.trs');
var arr = ['n0', 'n1', 'n2'];
for (var i = 0; i < trs.length; i++) {
    for (var j = 0; j < arr.length; j++) {
        var tds = trs[i].getElementsByClassName('tds ' + arr[j]);
        if (tds.length == 0) {
           for (var x = i + 1; x < trs.length; x++) {
               var tds_offset = trs[x].getElementsByClassName('tds ' + arr[j]);
               if (tds_offset.length > 0) {
                  trs[i].appendChild(tds_offset[0]);
                  break;
               }
           }
        }
    }
}

```

Answer: 
A singleton is an object which is the only instance of its type. Therefore, it makes most sense to define all non-function properties and methods directly on that singleton:

```
var singleton = {
    prop1: ...,
    prop2: ...,
    method1: function () { ... },
    method2: function () { ... }
};

```

Extending the singleton is easy:

```
singleton.prop3 = ...;
singleton.method3 = ...;  

```
If you want you constructor function to be a singleton, you are going to have to make a few tweaks to your code:

```
var Mui = function () {
    //the cached instance
    var instance;

    //rewrite the constructor
    Mui = function Mui() {
        return instance;
    };

    //carry over the prototype properties
    Mui.prototype = this;

    //the instance
    instance = new Mui();

    //reset the constructor pointer
    instance.constructor = Mui;

    //all the functionality
    instance.version = {
        Major  : '0',
        Minor  : '1',
        Bugfix : '0'
    };
    return instance;
};

Mui.prototype.sayHi = function() {
    alert('Hi');
};

var mui_1 = new Mui();
var mui_2 = new Mui();
alert(mui_1 === mui_2); //true​

```

You can see this working here: <http://jsfiddle.net/34vCH/3/>