With shiny selectize, avoid sorting of search results

Viewed 567

In the reproducible shiny application below, the searchable selectize field reorders values by the length of the character strings.

enter image description here

If I type 1 to the search field, 'Gears' appears above 'Cylinders' because the string is shorter. However, I want them in the original order, i.e., 11 above 12 above 13.

A thread in the selectize repo suggests to add something like sortField: [{field: 'name', direction: 'asc'}], but I don't manage to add this in the shiny context. So adding options = list(sortField = list(field = 'name', direction = 'asc')) to selectizeInput() has no effect.

library(shiny)
choices <- c(
  "11 Cylinders" = "cyl",
  "12 Transmission" = "am",
  "13 Gears" = "gear"
)

shinyApp(
  ui = fluidPage(
    selectizeInput(
      "variable", 
      "Variable:", 
      choices
    )
  ),
  server = function(input, output) {
  }
)
1 Answers
library(shiny)

# must have named vector for selectize.js to pick up on the injection
choices <- c(
  "11 Cylinders" = "cyl",
  "12 Transmission" = "am",
  "13 Gears" = "gear"
)

# define JS to inject for options
##asceding order
sort_asc <- I("[{field: 'name', direction: 'asc'},{field: '$score'}]")

##decending order
sort_desc <- I("[{field: 'name', direction: 'desc'},{field: '$score'}]")

JS_opts <- list(create=TRUE,
                labelField =  'name',
                searchField = 'name',
                sortField = sort_asc
                )

shinyApp(
  ui = fluidPage(
    selectizeInput(
      inputId = "variable", 
      label = "Variable:", 
      choices = choices,
      options = JS_opts
    )
  ),
  server = function(input, output) {
  }
)

Related