# Sorting Values with JavaScript

Lists and tables are often the best way to display data on the web; but you shouldn't have to worry about sorting that information manually. In today's tutorial, you're going to make a jQuery plugin that will put all your ducks in a row with JavaScript ease!

## Preface

So, how exactly does sorting work in JavaScript? It's not too complicated: any array object has a sort method. If you don't pass it any parameters, it will convert the objects in the array to strings, sort them pseudo-alphabetically, and return them. Usually, this is terrible; consider sorting the numbers 0 - 10 alphabetically. You would get this: [0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]. Fortunately, we can pass a function to the sort method. That function should take two parameters (the two items to be compared): then, it will return 0 if they are equal, a negative number if the first parameter takes precedence, or a positive number of the second parameter should come first. So numbers are actually the simplest thing to sort "manually":

Obviously, this will return 0 if the numbers are equal, a negative number if a should be first, and a positive number if b should be first.

We're going to look at sorting several different types of data, a few in multiple formats; but this will all be much more useful if we wrap it in a jQuery plugin, so let's start by setting up that shell!

## The Plugin Shell

If you're not familiar with writing jQuery plugins, check out Jeffrey Way's Screencast "You still can't create a jQuery Plugin?" It'll get you up to speed in no time if you're comfortable with jQuery! (true confession: I'd actually never written a plugin until I made this one).

We'll set up our plugin, called datasort, this way: we'll pass it an array of items to sort; we can specify four parameters.

• datatype (the type of data you're sorting)
• sortElement (the child element you want to sort by, if desired)
• sortAttr (the attribute you want to sort by, if desired)
• reverse (the direction they should sort in)

So a fully-modified call to our plugin might look like this:

Here's the plugin shell:

So here's how it'll work: we'll set up all the variables at the beginning. Then, if the datatype parameter is a string, we'll find the corresponding sort function in the datatypes object and sort with it; if the datatype parameter is a function, we'll sort with it. Finally, if the reverse setting is set to true, we'll reverse the order of the sorted items (since jQuery objects aren't true JavaScript arrays, the reverse function won't work on them; so we can use $.makeArray() to turn it into one; then, once it's reversed, we re-jquery-fy it!). ## Laying a Bit More Groundwork At the very lowest level, you can sort almost any type of data in one of two ways: we'll be calling them alphabetically and numerically. Let's create these two functions as properties of your base object. Pretty simple, eh? Simply normalize the two values, compare and return. The tricky part is parsing the data that we want to send to these functions; that's what we'll do now. However, there's one more thing. When sorting items in the array, we might not want to sort simply by the text of the element itself. The sortElement and sortAttr parameters of our plugin are to this end. For example, we will likely want to sort table rows based on a certain column of table cells. In that case, we'd use$('table tr').datasort({ sortElement : 'td.price' }). Or perhaps we want to sort a list of images by their alt attributes: \$('ul li').datasort({sortElement : 'img', sortAttr : 'alt'}). Because of all this, we need to add one more function to our base object:

It may look complicated, but it's not. We just create a jQuery object with each item; if sortElement is set, we use the children() method to get the right elements. Then, if a sortAttr is set, we get its value; if not, we get the element's text. We've set all this to an inner function, and return an object with two properites; these properties are the values we must parse and send to the appropriate base sorting function.

This probably seemed like a lot of prep work, but what we were really doing is abstracting as much code as possible. This way, they'll be much less repeat code, because the important actions have been bundled away as functions.

## Sorting Words and Numbers

We're finally here: the fun part! We'll start by building two simple functions for our datatypes object. These will simple pass values to base.extract() and then pass those return values to the appropriate sorting class.

Our alphabetic sorter should be obvious. The number sorter does a bit more: before passing the extracted values on, it strips out a dollar sign at the front. I've kept this regular expression simple, but you could parse a lot of different number formats here if you wanted to get complex. Let's give our evolving plugin a try; create a basic html page:

I've included a table and two lists (and I've styled them briefly). Take note of our plugin calls: we're using the default datatype for the table, but sorting by the table cells with a class of last; try changing this to 'td.first.' Then, we sort the lists numerically, and reverse one of them. Here's the proof of our labours:

Pretty nice, but those were relatively simple values; what if we want to be able to sort multiple formats for one type?

## Sorting Dates

There are a number of different ways to write dates, which makes it pretty tricky to parse them for sorting. However, we can cover most of them with this:

So what are we doing here? First, here's the logic: if all the dates are formatted YYYYMMDD, they will sort correctly with numerical sorting. Our parser can sort the following date formats:

• YYYY-MM-DD
• YYYYMMDD
• DD/MM/YYYY
• month DD, YYYY

First we strip our dashes, which will leave YYYY-MM-DD ready for parsing. Then, we replace every month name or abbreviation with its number value. Finally, we have to rearrange the numbers for DD/MM/YYY and month DD, YYYY. That's what the last two expressions do. To give this a try, paste this list into our HTML:

And call it with this:

Is this a perfect date parser? Not by any means; we can't sort DD/MM/YY, because there's no way to know what century this is in. Also, we can't tell the difference between DD/MM/YY and MM/DD/YY, so we just have to choose one.

## Sorting Time

Sorting time values must be one of the most difficult values to sort: we need to be able to accept 12-hour time, 24-hour time, and values with or without AM/PM tags and seconds. I think it's easiest to sort time alphabetically, even though its all numbers. Why? Consider these two timestamps: 00:15:37 and 12:15. The first one should come first, but if we sort them by number they'll be parsed as floats, and end up like 1537 and 1215. Now, the second value will come first. Also, when sorting alphabetically, we don't have to take out the colons (parseFloat() would choke on them). So here's how it's done.

Let's go through this line by line.

We start with our variables: our extracted values and a regular expression to check for PM label.

Next, we'll start a for loop, going through each of the values we're sorting; first, we split it into an array at the colons. We create an easy way to get to the last items of the array: our 'last' variable. Then, we test our PM regex on the last item in our array; if it returns true, this value has the PM tag. Therefore, we'll add 12 to the first item in our array, which will be the hour value; we do this because we need all the values to be formatted in 24-hour time. (Note that to do this, we must convert it to a number, add 12, and then turn it back into a string). Finally, we use the PM regex again to remove that label from the last item in the array.

In this last chunk, we check the hour value for two conditions: is it less than 10? and does the string have only one character? This is important because a value like 08 will parse as 8 and be less than 10; but we're trying to see if we need to add a zero to the front. If the string has only one character, then we add the zero, so 3 becomes 03. This will keep things in order!

Before joining the array, we remove any AM labels. So now this . . .

. . . can be sorted with this . . .

And we're done! Behold the fruits of our labour:

## More Random Values

We've set up our jQuery plugin so that users can pass sorting functions as the datatype parameter. This allows us to easily extend the plugin, although we don't have access to the base 'class' from the plugin call. We can easily write a function to sort psudeo-ratings:

This uses the simplest regular expressions possible to sort a list like this:

## That's a Wrap!

Now you're in the know: sorting values in JavaScript really isn't as hard as you might have thought. You can imagine this being useful to sort a table, with something like this:

(Try replacing the jQuery code for the table in the first example with this!)

Of course, we could improve this plugin a lot; for example, we could have it check the rel atttribute for a datatype if one isn't given as a parameter, and default to alpha if there is no rel. But that's aside from the sorting.

In sum, to sort with JavaScipt, we follow these steps:

1. Determine the different formats you want to sort.
2. Decide what format you want to sort in.
3. Sort the array of items with the sort() method, passing in a function that will convert the two items to your desired format before comparing them

Have a datatype to add to our plugin? Have a better way of sorting one of these? Let's hear it in the comments!