Custom Sorting for a Numeric Column with NaN Values in Kendo UI Grid for Angular
Environment
| Product | Progress® Kendo UI® for Angular Grid |
Description
The sorting functionality does not work as expected when NaN (Not-a-Number) values are presented. This article demonstrates how to sort or group NaN values together.
This KB article also answers the following questions:
- How can I sort numeric columns containing NaN values in Kendo UI Grid for Angular?
- Is there a way to group NaN values together when sorting a numeric column in Kendo UI Grid for Angular?
- What adjustments can I make to sort a numeric column with NaN values in Angular Kendo UI Grid?
Solution
In JavaScript a NaN value is not equal to any value, including itself. To sort numeric columns containing NaN values in the Kendo UI for Angular Grid, use the compare property of the SortDescriptor. This approach allows you to change the default sorting logic to accommodate NaN values.
Here is an example of how to use the compare property within the SortDescriptor to customize the sorting logic when NaN values presents. The example moves NaN values at the beginning when ascending order is used.
import { SortDescriptor } from '@progress/kendo-data-query';
public sortDesc: SortDescriptor[] = [
{
field: 'UnitPrice',
dir: 'asc',
compare: (a, b) => {
if (isNaN(b.UnitPrice)) return 1; // Move NaN at the beginning
if (isNaN(a.UnitPrice)) return -1;
return a.UnitPrice - b.UnitPrice; // Sort numbers normally
},
},
];
You can adjust the logic to show the NaN values at the end of the list when descending order is used:
import { SortDescriptor } from '@progress/kendo-data-query';
public sortDesc: SortDescriptor[] = [
{
field: 'UnitPrice',
dir: 'desc',
compare: (a, b) => {
if (isNaN(a.UnitPrice)) return 1; // Move NaN to the end
if (isNaN(b.UnitPrice)) return -1;
return b.UnitPrice - a.UnitPrice; // Sort numbers normally
};
},
];