reactable icon indicating copy to clipboard operation
reactable copied to clipboard

FR: ability to set custom sort functions

Open khusmann opened this issue 6 months ago • 1 comments

Hello, thanks for this awesome package! I'm doing a lot of work with list-cols and struct-cols with custom cell and aggregate render functions. It's all working great, except when I try to sort by these columns.

To remedy this, what would be really nice is the ability to have sortCell and sortAggregated options in my colDef as Javascript comparator functions. For example, the following would sort a list-col by the number of elements in the column:

df <- tibble(
  a = list(
    list(1, 2, 3),
    list(1),
    list(1, 2, 3, 4),
    list(1, 2),
    list(2),
  )
)

reactable(
  df,
  columns = list(
    a = colDef(
      sortCell = JS("
        function(a, b) {
          return a.length - b.length;
        }
      ")
    )
  )
)

Similarly, the following would sort a struct-col by the "sortkey" property:

df <- tibble(
  a = list(
    list(sortkey = 1, foo = "hello"),
    list(sortkey = 10, foo = "world"),
    list(sortkey = 2, foo = "foo"),
    list(sortkey = 10, foo = "bar"),
    list(sortkey = 8, foo = "baz")
  )
)

reactable(
  df,
  columns = list(
    a = colDef(
      sortCell = JS("
        function(a, b) {
          return a.sortkey - b.sortkey;
        },
      ")
      cell = JS("
        function(cellInfo) {
          return cellInfo.foo;
        }
      ")
    )
  )
)

sortAggregated would work exactly the same way, but apply to aggregated cells.

Without sortCell and sortAggregated I am resorting to populating my reactable with my desired sortkeys, storing all my actual data in the .meta object, and then doing lookups in my cell and aggregated renderers... Quite a headache, as you can imagine!

Anyway, thanks again for the awesome pkg, and please let me know if there are any other approaches to do this I've overlooked!

khusmann avatar Jul 19 '25 18:07 khusmann

Noted, I will link any other custom sort issues I remember here as well: https://github.com/glin/reactable/issues/368

This was supposed to be on the backlog years ago, but just never got done.

For now, yep, I'd recommend the same rough workaround of putting sort keys in the data.

glin avatar Aug 04 '25 02:08 glin