0
votes

I want sort the kendo grid column. In the below screen shot i need sort the WBS column either ascending or descending. In that column have that values like 1.1, 1.1.1, 1.2.1, 1.2.1.1, 1.2.1.2, 1.3, 2, 2.1, 2.1.1, 2.2 etc., enter image description here

1

1 Answers

1
votes

Basically you need to define an ad-hoc compare function for WBS column. This is possible using columns.sortable.compare.

Now, the question is inventing a function that is able to compare two values as you need.

It comes to my mind doing the following:

  1. Split the original value separated by "." in an array of values. Ex: "10.1.2" becomes [ "10", "1", "2" ].
  2. Compare one by one the values of the arrays keeping in mind that one might be shorter than the other which means that is smaller (i.e. 10.1 is smaller 10.1.1).

This would be something like:

columns   : [
    ...
    { 
        field: "wbs", 
        width: 150, 
        title: "WBS",
        sortable: {
            compare: function (a, b) {
                var wbs1 = a.wbs.split(".");
                var wbs2 = b.wbs.split(".");
                var idx = 0;
                while (wbs1.length > idx && wbs2.length > idx) {
                    if (+wbs1[idx] > +wbs2[idx]) return true;
                    if (+wbs1[idx] < +wbs2[idx]) return false;
                    idx++;
                }
                return (wbs1.length > wbs2.length);
            }
        }
    }
    ...
]

NOTE: As I said before and as result of the split, what I get in the arrays are strings. So it is pretty important that we use a little trick for comparing the values as number that is prepend a +. So when I do if (+wbs1[idx] > +wbs2[idx]) I'm actually comparing the values on wbs1[idx] and wbs2[idx] as numbers.

You can see it here: http://jsfiddle.net/OnaBai/H4U7D/2/