## 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!