How to make sorting key insensitive in ag-grid?
Note that by now you can just set the accentedSort
property in the GridOptions
to true
to achieve case-insensitive sorting. See here for more information.
If you use the custom comparator solution from wentjun please make sure to only apply it to string columns or, when applying to all columns, check if the value is a string. Otherwise the sorting won't work anymore on number based columns:
const customLowerCaseComparator = (valueA, valueB) => {
if (typeof valueA === 'string') {
return valueA.toLowerCase().localeCompare(valueB.toLowerCase());
}
return (valueA > valueB? 1 : (valueA < valueB ? -1 : 0));
};
This can be done by using a custom sorting function on the particular column that requires case-insensitive sorting.
For instance, for your columnDefs
, if you require the name
column to be sorted case insentitve, we pass the customComparator
as the value for the comparator
property. In your ngOnInit,
this.columnDefs = [
{
headerName: 'Name',
field: 'name',
sort: 'asc', // optional, allows grid column to be sorted on init
comparator: customComparator
},
// other columns
];
Then, we define the customComparator such that it carries out case-insentitive sorting. We do so by converting the values to lowercase on the custom comparator.
const customComparator = (valueA, valueB) => {
return valueA.toLowerCase().localeCompare(valueB.toLowerCase());
};
EDIT: I have forked and recreated a demo from the original ag-grid demo to demonstrate the usage of the above comparator. Refer to the constructor() method for the relevant details.