How to sort/order a table with a transformer

Hi there

I'm working on a server side pagination and I'm trying to order a query by a specific value (which is a table.sortedColumn value)

Problem is : I don't know how to use transformers.

Here's the idea of what I'm trying to achieve (with lots of mistakes)

let data = {{query.data}}
let order = {{table1.sortedColumn}}

let filtered = data.sort(x=>x.order)

return filtered

Hi @webloomers

you should change the line with something like:

let filtered = data.sort((a,b) => a[order]-b[order])

Array.sort optionally accepts a comparator function to evaluate your custom parameter.

If order is a number, then a[order]-b[order] results in ascending ordered array and b[order]-a[order] a descending one.
You can add more logic in that function if you need.

Hope this help

Hi abusedmedia, thanks for your quick reply, unfortunately it doesn't seem to work

Here's the whole code with your suggested edit

let data = {{query.data}}
let order = {{table1.sortedColumn}}

let filtered = data.sort((a,b) => a[order]-b[order])

return filtered

It doesn't seem to order anything. I tested with a static value for order for testing purposes and it doesn't work either. Query stays on its default order (first column).

Hi @webloomers

you are right, the transformer had further issues.

Here a working code using the default query of a blank project returning a sorted array based on an arbitrary parameter:

const order = 'quantity'
return formatDataAsArray(data).sort((a,b) => a[order]-b[order])

You can see that data is a reserved keywork that represents the original query.data and, since sort is an Array method, formatDataAsArray is required if the original source is a map.

Hope this help

@abusedmedia my data was already an array so it's not that. Your initial suggestion does show run correctly, just not filtered as planned

Update : for some reason this other approach works

let order = {{ table1.sortedColumn }}

sortedArray = data.sort((a, b) => a[order].localeCompare(b[order]))

return sortedArray

How would you then order DESC or ASC if clicking on the same event handler twice and/or repeatedly ?

Nevermind I found the solution for my last question. For those of you interested, there is a property called table1.sort['0'].desc (true or false) so I just had to add some conditioning.

Thank you so much for your support.

Good to hear you've solved!

By using localeCompare for the comparison means that your param value is a string type instead of a number.

Cheers.