I want to create a custom parator to sort column asc/desc, but in both situations, I want to keep all empty (null) values at the end of the list
I use valueGetter to return a proper string value/null.
I want to create a custom parator to sort column asc/desc, but in both situations, I want to keep all empty (null) values at the end of the list
I use valueGetter to return a proper string value/null.
Share Improve this question asked Mar 3, 2021 at 12:13 DominikDominik 1,3451 gold badge18 silver badges28 bronze badges 1- 1 please let me know if you are facing any issue with the below answer. Thanks! – Guruprasad mishra Commented Mar 4, 2021 at 9:41
1 Answer
Reset to default 9I think you can achieve this in 2 ways
First: use a parator for the column you want to use custom sort
columnDefs: [
{
field: 'columnName',
parator: (a, b, nodeA, nodeB, isInverted) => {
if (a === b) {
return 0;
}
// for null
else if (a === 'null') {
return isInverted ?-1: 1;
}
else if (b === 'null') {
return isInverted ? 1: -1;
}
else {
return a.localeCompare(b);
}
}
}]
- a,b: The values in the cells to be pared. Typically sorts are done on these values only.
- nodeA, nodeB: The Row Nodes for the rows getting sorted. These can be used if more information, such as data from other columns, are needed for the parison.
- isInverted: true for Ascending, false for Descending.
Second: use postSort mechanism, it will get called once everything is sorted
<GridOptions> {
postSort: this.postSort
}// add this to grid options
private postSort = function(rowNodes) {
// null value data will be sorted at the end
function checkNull(node) {
return node.data.Id === null ; // if id is column is the one we are chceking
}
function move(toIndex, fromIndex) {
rowNodes.splice(toIndex, 0, rowNodes.splice(fromIndex, 1)[0]);
}
var nextInsertPos = rowNodes.length; //last index
for (var i = 0; i < rowNodes.length; i++) {
if (rowNodes[i].data && checkNull(rowNodes[i])) {
move(nextInsertPos, i)
nextInsertPos++;
}
}
}