Search code examples
angularag-gridcomparatorag-grid-angular

custom sorting in Ag-grid


Below is header of ag-grid applied with custom sorting

{
        headerName: "StudentId",
        field: "StudentId",
        width: 140,
        editable: false,
        enableRowGroup: true,
        comparator: (valA, valB, n1, n2, inverse) => {
          return valA.localeCompare(valB);

        },
        sortingOrder: ['desc', 'asc'] 
   }

The reason I added a custom comparator because data is like

   S19
   S129
   S176
   S99
   S433
   S10

and after applying sorting to mentioned header you will get result in column like this

   S10
   S129
   S176
   S19
   S433
   S99

I am pretty sure some of you get confused by looking the result but it's correct because data contain alphabet as well as number so it is string and comparator working fine according sorting of string.

But i want result like this because it is human quick readable format.

S10
S19
S99
S129
S176
S433

Is it possible to do ??


Solution

  • This is less of a angular/ag-grid question as it is a question to design an algorithm for your desired sort behavior. It seems you've figured everything out except the comparator function.

    But we need some more details. From your small example it looks like your algorithm can simply cut off the first char of each string, and simply sort by the numbers remaining. But what other kind of strings will you be expecting? Will each string always be 'S' followed by digits? If that's the case then what I just described will work.

    But if each string will have x number of characters followed by y number of digits, then you will need to split your strings into two parts (chars & digits). Then sort first by chars and then by digits.

    Edit: Op has specified that the string is always an 'S' followed by digits, so I'm writing the custom comparator function here.

        comparator: (valA, valB, n1, n2, inverse) => {
          const digitsA = parseInt(valA.substring(1));
          const digitsB = parseInt(valB.substring(1));
          return digitsA - digitsB;
        }
    

    What this basically is doing is extracting the digits from each string, converting them to numbers and simply returning the difference. Note that if the returned value is less than 0 than it means A comes before B in the list.