In ng2-smart-table of angular 2 sorting functionality is case sensitive. Are there any options to make sorting table data as case insensitive?
Asked
Active
Viewed 8,251 times
2 Answers
11
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;
}
}
}
6
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]);
});
}
}

Wojciech K
- 952
- 7
- 16
-
where to insert this code? is this custom function? – Revathi Sekar Nov 08 '17 at 09:10
-
1As Lumix wrote, you can provide the attribute compareFunction in table configuration: [Documentation with all table configuration properties](https://akveo.github.io/ng2-smart-table/#/documentation) – Wojciech K Nov 08 '17 at 09:21
-
Is there an error? Can you please provide code or more details? – Wojciech K Nov 08 '17 at 09:31
-
1organization_name: { title: 'Organization Name', //I added that code here filter:true, sort:true, editable:true, addable:true, width: '25%', }, – Revathi Sekar Nov 08 '17 at 09:38
-
The code from Lumix's answer? In that case try changing **compareFunction(** to **compareFunction: (** . If it still doesn't work, please edit your question with the current code and error message – Wojciech K Nov 08 '17 at 09:46
-
it is still not wrkng :( – Revathi Sekar Nov 08 '17 at 10:45
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158599/discussion-between-wojciech-k-and-revathi-sekar). – Wojciech K Nov 09 '17 at 11:11