Home > other >  Ag Grid Sorting based on specified characters in the data
Ag Grid Sorting based on specified characters in the data

Time:12-30

I have a serial number column that I need to sort by the last few digits in Ag Grid (for React):

Here's an example of the default sorting:

references

Whereas instead of:

HS790022045
HS790022044
HS790022042
HS790022040
HS770022050
HS770022048
HS770022046
HS770022043

I'd like to see:

HS770022050
HS770022048
HS770022046
HS790022045
HS790022044
HS770022043
HS790022042
HS790022040

These are serial numbers, so the "prefix" is the model, and then they're model year 22, and then the last 3 digits are the numbers that should be sorted sequentially.

I'm thinking there's a way to do this at the column state level:

const SORT_MODEL = [
  {
    colId: 'RequiredDate',
    sort: 'desc',
    sortIndex: 0,
  },
  {
    colId: 'Reference',
    sort: 'desc',
    sortIndex: 1,
  },
]

gridColumnApi.applyColumnState({
  state: SORT_MODEL,
  defaultState: { sort: null },
})

Or possibly at the column definition level using comparator, but I'm not sure how...

  {
    field: 'Reference',
    headerName: 'Reference',
    comparator: ????????
  },

In SQL, I could use something like this to accomplish this:

ORDER BY RIGHT(Reference,3) DESC

Probably something simple I just can't think of?

CodePudding user response:

You should use the column comparator with a custom comparator function like this:

const comparator = (curr, next) => {
  const currVal = parseInt(curr.slice(-3), 10);
  const nextVal = parseInt(next.slice(-3), 10);

  if (currVal === nextVal) { return 0; }

  return currVal < nextVal ? -1 : 1;
}

const columnDefs = [
  { field: 'reference', comparator }
];

See a working example here: https://plnkr.co/edit/QrpqjZFS8k4t6hO7

  • Related