The javascript array .sort() function can take an optional parameter that allows you to define your own comparison operator. If you don't supply it, the default comparison will be applied between elements whilst sorting the array. eg,
x = ['aaaaaaaa', 'bbbbb', 'x', 'dd', 'zzz']
["aaaaaaaa", "bbbbb", "x", "dd", "zzz"]
x.sort()
["aaaaaaaa", "bbbbb", "dd", "x", "zzz"]
x.sort(function(a, b) { return a.length > b.length ? 1 : -1 })
["x", "dd", "zzz", "bbbbb", "aaaaaaaa"]
In the second case, I am sorting by string length rather than the default lexicographical string sort.
The problem:
I have a column of values client-side representing nice "WebTwoPointZero"-ified dates. These values could be a datestamp - "18/01/2012" or any of the following:
- Moments ago
- 1 minute ago
- X minutes ago
- 1 hour ago
- X hours ago
- Today
- Yesterday
- X days ago
I need to be able to sort an array of any random combination of these values.