Reputation: 107
In ng2-smart-table of angular 2 sorting functionality is case sensitive. Are there any options to make sorting table data as case insensitive?
Upvotes: 6
Views: 8551
Reputation: 319
Just wanted to throw out if you implement this to make sure you add a : after compareFunction. As shown below...
columns: {
group_name: {
title: 'Groupname',
compareFunction:(direction: any, a: any, b: any) => {
// Converting strings to lowercase
let first = typeof a === 'string' ? a.toLowerCase() : a;
let second = typeof b === 'string' ? b.toLowerCase() : b;
if (first < second) {
return -1 * direction;
}
if (first > second) {
return direction;
}
return 0;
}
}
}
Upvotes: 11
Reputation: 1051
You can provide your custom sorting function as the 4th argument in the sort() method.
Example:
let COMPARE_INSENSITIVE = (direction: any, a: any, b: any) => {
// Converting strings to lowercase
let first = typeof a === 'string' ? a.toLowerCase() : a;
let second = typeof b === 'string' ? b.toLowerCase() : b;
if (first < second) {
return -1 * direction;
}
if (first > second) {
return direction;
}
return 0;
}
ng2-smart-table uses the following default COMPARE function:
export class LocalSorter {
protected static COMPARE = (direction: any, a: any, b: any) => {
if (a < b) {
return -1 * direction;
}
if (a > b) {
return direction;
}
return 0;
}
static sort(data: Array<any>, field: string, direction: string, customCompare?: Function): Array<any> {
const dir: number = (direction === 'asc') ? 1 : -1;
const compare: Function = customCompare ? customCompare : this.COMPARE;
return data.sort((a, b) => {
return compare.call(null, dir, a[field], b[field]);
});
}
}
Upvotes: 6