Plugin for sorting lists


I’d like to build a plugin that takes a list (represented as a string) of pairs of numbers and sorts it by the second number. Here’s the JS script:

function sort_me(list_to_sort) {
  let list = JSON.parse(list_to_sort);
  return JSON.stringify(list.sort((a, b) => a[1] - b[1]));
console.log(sort_me('[[1, 3], [2, 1], [3, 5], [4, 9]]'));

Result on console: [[2,1],[1,3],[3,5],[4,9]]

In a Bubble plugin Element I declared a Field ‘list_to_sort’ (type text) and an Exposed State ‘sorted_list’ (type text).

In the Update code I wrote:

function(instance, properties, context) {
    let list = JSON.parse(list_to_sort);
    let result = JSON.stringify(list.sort((a, b) => a[1] - b[1]));
    instance.publishState('sorted_list', result);

It keeps throwing an error :frowning: . If I comment out the two let lines and write ‘Hello’ instead of ‘result’ it correctly outputs ‘Hello’, so the config is ok.

I thought maybe the .sort function doesn’t work in Bubble, but it works ok in the HTML element on a page.

Any ideas how I can make the plugin work?

some tips:

  • when you write multiline code here add ``` at the beginning and end of the code, you get a nicer code formatting:
let x = 'hello';
  • if your plugin throws an error try inspecting the console on chrome, it should log some more informations (I still need to figure out why firefox has less logs)

probably you need to change the line with the list creation like this:
let list = JSON.parse(properties.list_to_sort);

1 Like

OMG, yes, that was the solution! Thank you @dorilama!

Happy to help :slight_smile:

1 Like