0

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.

1 Answers1

1

The biggest problem here is writing a method for converting relative time to absolute time. After writing a method that can do that, you can sort the data by comparing the timestamps.

To write a method like that, you'll need to catalog and organize all of the different formats you're willing to accept. Once deciding on the formats, you can write a series of regular expressions to identify them, use capturing groups to extract any important values, then pass those values to a function to be added or subtracted from the current datetime, based on keywords like 'before' and 'ago' and the location of those words in the phrase.

Regardless, this is an incredibly complicated process. Have fun.

There is also Stackoverflow question on this exact subject from a few years ago. You might find some good advice there.

Community
  • 1
  • 1
Frank Crook
  • 1,466
  • 12
  • 19