Skip to main content Skip to footer

Exclude Pinned Rows While Sorting in JavaScript

Pinned rows while sorting example

Background:

By default, the standard sort functionality of Wijmo FlexGrid when clicking on a column header sorts the entire grid. Sometimes users want particular rows to remain pinned or frozen at the top and not be affected by sorting. With a bit of custom code in JavaScript, you can accomplish this by providing a custom sort converter that excludes pinned rows from the sort logic.

Steps to Complete:

  1. Provide a custom sortConverter function on the grid’s CollectionView.
  2. Ensure that a unique identifier is present on the data items for the pinned rows.

Getting Started:

Provide a custom sortConverter function on the grid’s CollectionView

Assigning a custom sortConverter overrides the default sort behavior and allows you to determine how values are compared for sorting. In this case, the converter checks whether a row is pinned and forces it to remain at the top (or bottom), effectively excluding it from the normal sort operation.

<div id="theGrid"></div>
import * as wjcGrid from '@mescius/wijmo.grid';
import * as wjcCore from '@mescius/wijmo';

const items = getData();

const grid = new wjcGrid.FlexGrid('#theGrid', {
  itemsSource: items
});

// Assign a custom sort converter
grid.collectionView.sortConverter = function (sd, item, value) {
  const pinnedRowCount = 3; // number of pinned rows

  // If this item is pinned, force its sort position
  if (item.id < pinnedRowCount) {
    return sd.ascending ? -Infinity : Infinity;
  }

  // Otherwise, use the default value
  return value;
};
  • In this example, rows with id < 3 are treated as pinned.
  • The sort converter checks this condition and assigns a forced sort value to keep these rows fixed.

 

Ensure that a unique identifier is present on the data items for the pinned rows

The sort converter needs a reliable way to identify which rows are pinned. Adding a unique identifier (such as an id property) to each data item allows the converter to determine whether a row should be excluded from sorting.

function getData() {
  return [
    { id: 0, country: 'PinnedRow1', value: 100 },
    { id: 1, country: 'PinnedRow2', value: 200 },
    { id: 2, country: 'PinnedRow3', value: 300 },
    { id: 3, country: 'Canada', value: 50 },
    { id: 4, country: 'Germany', value: 150 },
    { id: 5, country: 'Japan', value: 120 }
  ];
}

 

With this JavaScript setup, rows designated as pinned using a unique data property remain unaffected when users sort the FlexGrid by clicking column headers. Only non-pinned rows participate in sorting, while pinned rows stay fixed at the top (or bottom, depending on sort direction).

Happy coding!

Andrew Peterson

Technical Engagement Engineer