Sort of Confusing

Some of the worst JavaScript code I have seen has to do with sorting data.

JavaScript has a flexible array sort method, but it takes a while to get the hang of using it. Programmers seem to do fine sorting a simple array, but if the data format is something just a bit less trivial, many JavaScript programmers throw their hands up in the air. You can almost see the frustration in the code (sometimes in the comments).

One common situation that many people seem stumped by is sorting an array of objects based on a given key.

Suppose we have this array of objects:


Now suppose you want to sort the array by any of r, g, or b, and that you want to support both ascending and descending sorts. How would you approach the problem?

Back To Basics

Remember that to sort an array, you just invoke the “sort” method that belongs to JavaScript’s array type.


That works for sorting an array of strings, but it doesn’t work for sorting an array of numbers. That’s why even the novice JavaScript programmer recognizes the code for sorting numeric values.

    function sortNumber(a,b) {
        return a - b;


JavaScript lets us pass in a function that is used to judge whether a value is less than, equal, or greater than another value.

Having that hook into the guts of the sort method lets us solve just about any sorting problem. But how?

Here’s a solution for the {r,g,b} problem above, where I want to be able to sort on r, g, or b in either ascending or descending mode.

    function sortByKey(arr,key,direction) {
        function sortNumeric(a,b) {
            if (direction=="ASC") {
                return a[key]-b[key];
            } else {
                return b[key]-a[key];   
        return arr.sort(sortNumeric);

The outer function is a handy way to keep the key (what we’re sorting on) and direction (which way we’re sorting) around, since there is no simple way to pass that information into the sort method. Remember that the inner function has access to the outer function’s variables, and that includes the parameters that come in.

Oh, by the way, the code is easier to understand if you recall that obj.r is the same as obj[“r”]. We can pass in a string to a function and use that string as a key to get a value. That way we get around the need to write a separate evaluation function for each key.

Call the function like this:


to sort the objects in descending r order, or


to sort the objects in ascending g order.

Real Life Intrudes

Sometimes the data is not nice. You may have blank (empty or missing) spots in your data. In Excel, whether you sort ascending or descending, cells that are empty always show up at the end of the list. I recently needed to match that functionality in an Adobe AIR utility program I was writing. Here’s the code (blank cells from Excel ended up as empty strings in my data).

    function sortByKey(arr,key,direction) {
        function sortNumeric(a,b) {
            var c=a[key],d=b[key];
            if (direction=="ASC") {
                return (c==="")-(d==="") || c-d;
            } else {
                return (c==="")-(d==="") || d-c;   
        return arr.sort(sortNumeric);

A bit longer, codewise. But exactly what I needed for my data.

Once you get the hang of using inner functions, JavaScript’s sort method makes much more sense. It’s easy to extend this idea to accomodate other kinds of data (like strings), or to support secondary sorts, where a second key can be used to break ties.


The Object Slinger

The more JavaScript code I write, the less secure I am in thinking I have a handle on the language. Just when I settle on a way of doing something, a startlingly better way occurs to me.

JavaScript as Sexy Forest Nymph

JavaScript is a language that seems to have grown up without the sun shining on it. While Java is the bleach blonde fake-boob lifeguard chick surrounded by gawkers, JavaScript is a hauntingly mysterious gal in the forest that you can nearly catch a glimpse of as you scramble through blackberries and brambles.

Everyone seems to know the proper way to program in Java. It’s the language you learn in college. It’s formal. It’s strict. It’s how your mother would want you to code.

No one really seems to be sure of the “right way” to code in JavaScript. Or, rather, there are a lot of people who are sue how to program in JavaScript, but they don’t all agree with each other. It’s still the wild west.

When people start coding in JavaScript, many complain that it’s not like Java. Looking for Java in JavaScript is looking for heartbreak. Instead, treat JavaScript as a magical version of C that allows you to stuff objects and functions into variables. Sometimes you don’t even have to stuff them into variables–-you can create them on the fly and pass them around.

Maybe if C had been more like JavaScript we never would have moved to C++.


I remember that when I programmed in C, I’d often get into a situation where I had a function that had been returning one value and now I wanted it to return two values. I felt painted into a corner.

Sometimes I’d hack it so both values got returned together. If I knew x was in the range 0-15, and y was in the range 0-15, I’d return x*16+y and the calling function would do the math to break the values out into two pieces. In more difficult situations, I’d have to make a struct and pass a pointer to that around. Doesn’t sound like a big deal, really, but it broke the flow and made everything ugly.

In C++ or Java, you’re typically thinking about classes the whole way through. It’s a mindset where you’re not mad at having to put together a struct to hold structured data, you’re resigned to thinking in classes. OK, stop staring at the nymph and pay attention. I’m going to show you some code.

It’s Different

JavaScript is different. I don’t have to hack around like I did in C, and I don’t have to think in classes. I just return an object, and I can sling that object into existence right at the last minute, right in the return statement.

Here’s a ridiculous function that always returns an object that holds the numbers 10 and 12. A better example (and a rather common one) would be a library that does complex math. For illustration, this’ll do.

function giveMeX10Y12() {
    return {x:10,y:12};

The caller can easily pull the pieces apart:

console.log (obj.x,obj.y);

To me, this is what JavaScript programming is all about. It’s not about classes-–it’s about objects. It’s lightweight and comfortable, once you unlearn other languages and gain JavaScript chops.

Spaghetti Western

When you start programming JavaScript, you’re going to write some big plates of spaghetti. You’ll know you’re doing it badly. But learn to think in JavaScript and your code will be clean and easy to debug.