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

Implement Stable Sorting for Grouped Data in Chrome

Environment

Product Progress® Kendo UI® Grid for jQuery
Operating System All
Browser All
Browser Version All

Description

How can I implement stable sorting for grouped data in Google Chrome when using the Kendo UI jQuery Grid widget?

Solution

The implementation of the built-in sorting algorithm in Google Chrome is not guaranteed to be stable.

A non-stable sorting algorithm might cause items with the same sorting order to change places. When the Grid is grouped by a given field, you can use the sort method in the group event handler to programmatically sort the items within each group in the preferred order.

The following example demonstrates how to apply a stable sort function by using a position field in the Grid.

<div id="grid"></div>

    <script>
      $("#grid").kendoGrid({
        dataSource: [
          { "Name": "Group1", "Value": 1 },
          { "Name": "Group1", "Value": 2 },
          { "Name": "Group1", "Value": 3 },
          { "Name": "Group1", "Value": 4 },
          { "Name": "Group1", "Value": 5 },
          { "Name": "Group1", "Value": 6 },
          { "Name": "Group1", "Value": 7 },
          { "Name": "Group1", "Value": 8 },
          { "Name": "Group2", "Value": 1 },
          { "Name": "Group2", "Value": 2 },
          { "Name": "Group2", "Value": 3 }
        ],
        height: 600,
        group: function(e){
          var groupedByName = false;
          e.groups.forEach(function(item){
            if(item.field === 'Name'){
              groupedByName = true;
              return;
            }
          })

          if(groupedByName){
            e.sender.dataSource.sort({
              field: 'Name',
              dir: 'asc',
              compare: function(a, b) {
                if(a.Name !== b.Name) {
                  return a.Name.localeCompare(b.Name);
                }

                return a.Value - b.Value;
              }
            });
          }
        },
        groupable: true,
        columns: ['Name', 'Value']
      });
    </script>

See Also

In this article