New to Kendo UI for jQuery? Download free 30-day trial

Position the Null Values Last When Sorting

Environment

Product Version 2019.3.917
Product Progress® Kendo UI® Grid for jQuery

Description

How do I show the null values at the end of the Grid when I sort it in any order?

Solution

Use the following custom function in the columns.sortable.compare configuration.

  columns: [{
    sortable: {
      compare: function (a, b, desc) {
        if (a.name === b.name)
          return 0;
        else if (a.name === null)
          return desc ? -1 : 1;
        else if (b.name === null)
          return desc ? 1 : -1;
        else if (desc)
          return -1;
        else
          return 1;
      }
    }
  }]

Example

  <div id="grid"></div>
  <script>
      var numbers = {
          "one"  : 1,
          "two"  : 2,
          "three": 3
      };

      var dataSource = new kendo.data.DataSource({
          data: [
          { id : 1, name : "a" },
          { id : 2, name : "b" },
          { id : 3, name : "c" },
          { id : 4, name : "d" },
          { id : 5, name : "e" },
          { id : 6, name : null },
          { id : 7, name : "g" }
      ],
      pageSize: 10,
      schema  : {
          model: {
              fields: {
                  id   : { type: 'number' },
                  name : { type: 'string' }
              }
          }
      }
      });

      $("#grid").kendoGrid({
          dataSource: dataSource,
          sortable: true,
          columns: [ { field: "id", title: "id" },
          { 
              field: "name", 
              title: "Name",
              sortable: {
                  compare: function (a, b, desc) {
                    if (a.name === b.name)
                        return 0;
                      else if (a.name === null)
                        return desc ? -1 : 1;
                      else if (b.name === null)
                        return desc ? 1 : -1;
                      else if (desc)
                        return -1;
                      else
                        return 1;
                  }
                }
              }]
      });
  </script>

See Also

In this article