Tips and tricks: Sorting of texts containing figures
30.11.2015
Today tip is about the way of sorting numeric values in a non-numeric format. In particular, we will take a look at an example of sorting component versions - e.g. "1.4.0.1". Values input in such a way are not sorted like numerals but like texts. In case, that some of the figures contains two or more characters, it will be sorted in a different way than we would expect:
1.1.0.0
1.12.0.1
1.3.0.0
1.4.0.0
The value 12 is sorted behind 1. However, we would expect such an order:
1.1.0.0
1.3.0.0
1.4.0.0
1.12.0.1
ObjectGears offers a solution in form of a function that creates a regular integer out of these "dotted" figures. The function will split the text according to the separator, it will add zeros to the left of each figure according to the parameter maxNumberLength and merges the strings in a single integer.
OG.TextUtils.CreateDottedText() and OG.TextUtils.CreateDottedText(minNumbers, maxNumbers, maxNumberLength)
Example:
var dt = OG.TextUtils.CreateDottedText(4, 4, 2);
var l = dt.ParseLong("1.12.4.1");
Result:
l = 1120401;
Now, you just need to create another column in the class (type integer) and create a rule (type Before saving a record), in which you will read text of the version, create a numeric version and save it into this new column.
After that you will define sorting in the class according to this new column.
Take a look also at the documentation.