Before Evalia took a job at Initech, her predecessor, "JR" had to get fired first. That wasn't too much of a challenge, because JR claimed he was the "God of JavaScript". That was how he signed each of the tickets he handled in the ticket system.

JR was not, in fact, a god. Since then, Evalia has been trying to resuscitate the projects he had been working on. That's how she found this code.

``````function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
``````

This code sorts the elements in a drop down list, and it manages to do this in a… unique way.

First, we iterate across the elements in the list of options. We build a 2D array, where the first axis is the item, and the second axis contains the text caption and value of each option element.

Once we've built that array, we can `sort` it. Fortunately for us, when you sort a 2D array, JavaScript helpfully defaults to sorting by the first element in the second dimension, so this will sort by the text value.

Now that we have a sorted list of captions and values, we have to do something about the pesky old ones. So we iterate across the list to set each one to `null`. Well, not quite. We actually set the first item to null until the length is 0. Fortunately for us, the JavaScript `length` only takes into account elements with actual values, so this works.

Once they're all empty, we can repopulate the list by using our temporary array to create new options and put them in the list.

Credit to JR, I actually learned new things about JavaScript when wrying to understand this code. I didn't know how `sort` behaved with 2D arrays, and I'd never seen the `while`/`length` construct before, and was shocked that it actually works. Of course, I'd never gotten myself into a situation where I'd needed those.

The truly "god-like" thing is that JR managed to take the task of sorting a list of items and turned it into a task that needed to visit each item in the list three times in addition to sorting. God-like, sure, but the kind of god that Lovecraft warned us about.