TEST TEST

Alphanumeric sorting

iaian7 » blog   John Einselen, 8.10.09    

I came across a dark realisation last month – Javascript sorts lexicographically, not alphanumerically. After days of failed attempts and scouring the web for snippets, I finally came up with my own solution.

The first few lines are designed to prep results from an OS X file array (quite useful for developing Dashboard widgets in Dashcode!), but can be easily modified for other situations. The most important part to note is the .split(/(\d+)/) regular expression. This both splits and returns the string at every numeric section, giving us an array of alpha and numeric chunks. Each chunk is then compared; if one is greater or less than the other, the function returns the sorted value. If not, it keeps on checking to the end of (in this case) the file name. Not only does it allow for very specific alphanumeric sorting, but easily customizable results as well. For example, OSX places file names with a longer alphabetical string at the end before those with the same, but shorter, titles. This script accurately mimics the same behaviour.

function sortAlphaNum(a, b) { var x = a.split("/"); var y = b.split("/"); x = x[x.length-1].replace(/\\\s/g," ").split(/(\d+)/); // the split formatting is imperative, everything else can change y = y[y.length-1].replace(/\\\s/g," ").split(/(\d+)/); // the split formatting is imperative, everything else can change for (var i in x) { if (x[i] && !y[i] || isFinite(x[i]) && !isFinite(y[i])) { return -1; } else if (!x[i] && y[i] || !isFinite(y[i]) && isFinite(y[i])) { return 1; } else if (!isFinite(x[i]) && !isFinite(y[i])) { x[i] = x[i].toLowerCase(); y[i] = y[i].toLowerCase(); if (x[i] < y[i]) return -1; if (x[i] > y[i]) return 1; } else { x[i] = parseFloat(x[i]); y[i] = parseFloat(y[i]); if (x[i] < y[i]) return -1; if (x[i] > y[i]) return 1; } } return 0; }

Lastly, we ask Javascript to sort an array using the above function, like so:

array = array.sort(sortAlphaNum);

Let me know if you use this in any projects, I’d love to know! emoticon

bookmark